简体   繁体   中英

Iframe to parent using postMessage for cross domains

I am having trouble using postMessage, even after reading other posts online and on this website.

I have an iframe that is generate using var abc_iframe = document.createElement('iframe'). From my understanding I am suppose to attach an event listener to this to listen to message from within the iframe. I have tried:

1. abc_iframe.addEventListener("message", function(e){ console.log(e.data); }, false);
2. document.frames['id_iframe'].addEventListener("message", function(e){ console.log(e.data); }, false); 
(id_iframe right here being the id of the iframe)
3. WinJS.Application.addEventListener("message", function(e){ console.log(e.data); }, false);

None of these have worked. I am sending the postMessage from within the iframe using

1. parent.postMessage("message", "ms-appx://" + document.location.host);
2. window.parent.postMessage("message", "ms-appx://" + document.location.host);

The iframe content is hosted on another domain (not locally).

You need to attach to the window object, not the iframe, to receive messages from the iframe.

window.addEventListener(function(e) {}));

In the message you send you should include info that lets the parent identify the iframe sending the message, as all messages from all windows will be processed by this event handler.

Also note that addEventListener only works in some browsers. Older IE versions use attachEvent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM