I've been following this tutorial - http://www.youtube.com/watch?v=R2hOvZ7bwXU, which explains how to use postMessage to securely pass a message between iframe and parent - you basically end up with something like this - http://html5demos.com/postmessage2
My problem is that I need it to work the opposite way round (child to parent) and don't know how to target the parent window.
this is my receiver code (in the parent):
function handleMsg(e) { if(e.origin == "http://uc.dialogue.net") { let blah = e.data; alert(blah); } else { alert("error"); } } addEventListener("message", handleMsg, true);
and this is the sender function that is triggered by a simple form (in child):
let text = document.querySelector('.srchInput').value; window.parent.postMessage(text, "http://uc.dialogue.net");
Should I be targeting the parent in a different way?
Cheers Paul
Sending data from child iframe to parent window : Sending some data from the child iframe to the parent window is also pretty simple. 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.
Window.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.
Communicating directly between iframes is also possible by combining window. parent with target as defined above. In conclusion, the postMessage method is a more dynamic alternative to the single DOM, better suited if you load multiple pages in one iframe, but not always easier and it still requires the use of the DOM.
The window will get opened by using the iframe, and the communication could be done with the parent window from the child window. To call a parent window function, use the following syntax and also refer to the code given below.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent"; var eventer = window[eventMethod]; var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message"; // Listen to message from child window eventer(messageEvent,function(e) { var key = e.message ? "message" : "data"; var data = e[key]; //run function// },false);
Got it to work with the above in the parent page and the following in the child page -
parent.postMessage("loadMyOrders","*"); // `*` on any domain
Code copied from here.
Unpacked the accepted answer using newer ecma262 spec, and dropping ie8 support:
window.addEventListener('message', e => { const key = e.message ? 'message' : 'data'; const data = e[key]; // ... },false);
Relevant documentation:
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