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?
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.
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.
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').
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With