postMessage()生成错误“undefined不是函数” [英] postMessage() generates error "undefined is not a function"

查看:1983
本文介绍了postMessage()生成错误“undefined不是函数”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取 postMessage(),以便在iframe和我的主网站之间进行通信。但是,使用示例代码中给出的确切语法 MDN 上,我正在接受一个不错的未定义不是函数错误。我尝试了几件事,比如在Javascript中初始化iframe并将其附加到我的页面,但这给我留下了同样的错误。同样有选择我的iframe的单独选择器。

I'm trying to get postMessage() to work to communicate between an iframe and my main website. However using the exact syntax given in the example code on MDN, I am being presented with a nice Undefined is not a function error. I've tried several things, such as initializing the iframe inside Javascript and appending it to my page, but that left me with the same error. Same for have seperate selectors to select my iframe.

我有以下Javascript代码:

I have the following Javascript code:

<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发送消息,如下所示: p>

The script above tries to send a message to my iframe on the page, which looks like:

<iframe src="domain here/frameListener.html" class="editor"></iframe>

然后它有一个函数 receiveMessage 来捕获任何消息作为对主网页的响应发送。最后但同样重要的是,我已经尝试了这个问题中给出的答案:但这并没有解决我的问题。因此,它不是重复的。

It then has a function receiveMessage to catch any messages being send as a response to the main webpage. Last but not least, I've tried the answers given in this question: But that did not fix my problem. It is therefore not a duplicate.

如何摆脱此错误消息?

推荐答案

postMessage 不是jQuery函数,所以你需要获得实际的窗口 DOM元素和称之为:

postMessage is not a jQuery function so you need to get the actual window DOM element and call it on that:

 $('.editor').get(0).contentWindow.postMessage("A", "domain here");

此外,您需要访问 contentWindow iframe 的属性。以下是MDN文档的摘录:

Furthermore, you need to access the contentWindow property of the iframe. Here is an excerpt from the MDN docs:


otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow

对另一个窗口的引用;这样的引用可以是
,例如,使用iframe
元素的contentWindow属性,window.open返回的对象,或window.frames上的named或numeric
索引。

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.

这篇关于postMessage()生成错误“undefined不是函数”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆