chris.wilkinson
chris.wilkinson

Reputation: 321

window.postMessage not working from iframe to parent document

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?

Upvotes: 22

Views: 34386

Answers (2)

bN_
bN_

Reputation: 884

I've had exactly the same problem and had 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.

Upvotes: 11

James Lawruk
James Lawruk

Reputation: 31337

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

Upvotes: 6

Related Questions