Search code examples
javascriptjqueryhtmliframepostmessage

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


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?


Solution

  • 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.