Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.postMessage not working from iframe to parent document [duplicate]

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?

like image 696
chris.wilkinson Avatar asked Oct 02 '16 22:10

chris.wilkinson


People also ask

How do I transfer data from iframe to parent?

Sending data from child iframe to parent window : Whenever you embed an iframe, the iframe will have a reference to the parent window. You just need to use the PostMessage API to send data via the window. parent reference of the parent window.

Can iframe send message to parents?

postMessage() API allows you to send data from one window to another across domains. With postMessage , the embedded iframe site is able to send data to the parent window. Scripts in the parent window can then listen for the message event, and take action based on the data sent.

How do you send iframe to postMessage?

postMessage in your web app sends to the main document's window , not to the iframe's. Specify the iframe's window object: document. getElementById('cross_domain_page').

What does Window parent postMessage do?

postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.


1 Answers

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

like image 104
bN_ Avatar answered Nov 10 '22 00:11

bN_