我正在尝试让 postMessage()
在 iframe 和我的主网站之间进行通信。但是使用 example code 中给出的确切语法在 MDN ,我收到了一个不错的 Undefined is not a function
错误。我已经尝试了几件事,例如在 Javascript 中初始化 iframe 并将其附加到我的页面,但这让我遇到了同样的错误。相同的是有单独的选择器来选择我的 iframe。
我有以下 Javascript 代码:
<script type="text/javascript">
$(document).ready(function() {
$('.editor').postMessage("A", "domain here");
});
function receiveMessage(event)
{
if (event.origin !== "domain here")
return;
// Do something
}
window.addEventListener("message", receiveMessage, false);
</script>
上面的脚本尝试向页面上的 iframe 发送消息,如下所示:
<iframe src="domain here/frameListener.html" class="editor"></iframe>
然后它有一个函数 receiveMessage
来捕获作为对主网页的响应发送的任何消息。最后但同样重要的是,我尝试了 this question 中给出的答案。 : 但这并没有解决我的问题。因此它不是重复的。
我怎样才能摆脱这个错误信息?
最佳答案
postMessage
不是 jQuery 函数,因此您需要获取实际的 window
DOM 元素并在其上调用它:
$('.editor').get(0).contentWindow.postMessage("A", "domain here");
此外,您需要访问 iframe
的 contentWindow
属性。以下是 MDN 文档的摘录:
otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow
A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on window.frames.
关于javascript - postMessage() 生成错误 "undefined is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28211384/