window.postMessage not working from iframe to parent document

19,281

Solution 1

I've had exactly the same problem and have solved it by moving the "script" section above the iframe declaration. Here is the final code of the parent site :

<script>
    window.addEventListener('message', e => {
        console.log(e.data);

        if (e.origin == "http://localhost:8080"
            && e.data == "CallFunctionA") {
            FunctionA();
        }
    }, false);

    function FunctionA() {
        window.alert('FunctionA called')
    }
</script>

<html>

<body>
    <h1>Hello static web site !!!!</h1>

    <iframe name="ifu-frame" src="http://localhost:8080/index.html" />
</body>

</html>

And the content of the iframe is simply :

<button onclick="window.parent.postMessage('CallFunctionA', 'http://localhost:8081')">Call function A</button>

If I put the "script" section at the bottom of the document then it doesn't work anymore...

Solution 2

Ensure your callback function receiveMessage() is declared before passing it into the addEventListener method.

Here is your revised parent script:

var receiveMessage = function(event) {
    console.log("Recieved event " + JSON.stringify(event));
}
window.addEventListener("message", receiveMessage, true);
Share:
19,281
chris.wilkinson
Author by

chris.wilkinson

Updated on June 28, 2022

Comments

  • chris.wilkinson
    chris.wilkinson almost 2 years

    I'm trying to send a simple message from a child document (an iframe) back to its direct parent using the window.postMessage API.

    Within the parent document I have the following:

    window.addEventListener("message", receiveMessage, true);
    var receiveMessage = function(event) {
        console.log("Recieved event " + JSON.stringify(event));
    }
    

    Then, in the iframe I have the following:

    window.parent.postMessage('message', '*');
    

    Based on everything I've read, this should work and my log message should be written to the console. Except it's not working.

    I'm aware that using the * as the targetOrigin is not always secure, but at this point I just want to sort out the linkage.

    Any ideas or anything obvious that I'm missing?