Javascript 实现跨域通信

Javascript 实现跨域通信,javascript,typescript,Javascript,Typescript,使用TypeScript,我试图实现中提到的跨域通信 我的代码如下: var iframeElement = document.getElementById("myIframe"); iframeElement.document.contentWindow.postMessage('hello', '*'); 但是在文档后面的第二行中,我没有得到contentwindow的句柄 有人能提供解决方案吗?如果您所说的“句柄”是指您没有完成代码,那是因为contentWindow是iframel

使用TypeScript,我试图实现中提到的跨域通信

我的代码如下:

 var iframeElement = document.getElementById("myIframe");
 iframeElement.document.contentWindow.postMessage('hello', '*');
但是在文档后面的第二行中,我没有得到
contentwindow
的句柄

有人能提供解决方案吗?

如果您所说的“句柄”是指您没有完成代码,那是因为
contentWindow
iframelement
的属性,而不是文档的属性(顺便说一句,因为
document.getElementById
的结果是一个通用的
HtmlElement
,而不是一个iframe)

试试这个:

// Cast the result of getElementById, so you get an iframe and not a generic HtmlElement:
var iframeElement:HTMLIFrameElement = <HTMLIFrameElement>document.getElementById("myIframe");
// Then reference the contentWindow property of the iframe element
iframeElement.contentWindow.postMessage('hello', '*');
//强制转换getElementById的结果,这样您就得到了一个iframe而不是一个通用的HtmleElement:
var-iframelement:htmliframelement=document.getElementById(“myIframe”);
//然后引用iframe元素的contentWindow属性
iframelement.contentWindow.postMessage('hello','*');

欢迎访问SO。请参阅常见问题解答()。我们通常会突出显示代码内容,以便于阅读,而且我们通常不会签名。我不确定您在上面的问题中“句柄”是什么意思-您能再次解释这个问题吗?@user2108168很好-很高兴能提供帮助。