postMessage() 产生错误 "undefined is not a function"

postMessage() generates error "undefined is not a function"

我正在尝试让 postMessage() 在 iframe 和我的主网站之间进行通信。然而,使用 example code on MDN 中给出的确切语法,我收到了一个很好的 Undefined is not a function 错误。我已经尝试了几件事,例如在 Javascript 中初始化 iframe 并将其附加到我的页面,但这让我遇到了同样的错误。对于 select 我的 iframe 有单独的 select 也一样。

我有以下 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");

此外,您需要访问 iframecontentWindow 属性。以下是 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.