postMessage() generates error “undefined is not a function”

戏子无情 提交于 2019-12-07 07:21:24

问题


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.

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>

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>

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.

How can I get rid of this error message?


回答1:


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");

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

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.



来源:https://stackoverflow.com/questions/28211384/postmessage-generates-error-undefined-is-not-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!