cross domain iframe communication
If you need to send data to and from iFrames there are numerous different methods however alot of them are outdated or just to complicated. Why not use postMessage:
//on the sending end, within iframe
var domain = document.referrer;
postMessage(window.frameElement, 'http://'+domain);
//on the receiving end, the parent page
window.addEventListener('message',function(){
event.source.postMessage('{"somedata":"value", "ohmoredata":"value"}', event.origin);
},false);
You can send json object back and forth in order to easily send more than on piece of data with limited amount of calls to each iframe.
Also by using event.source and event.origin you do not need to hard code the domain values to each message, making the code reusage across multiple domains.
Written by Fay Pickering
Related protips
4 Responses
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/25501/profile-2015-2.jpg)
Didn't know about it. It seems to be supported even for IE8+ http://caniuse.com/#feat=x-doc-messaging
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/45057/74c714225754481aabee8ab22408cd2d.png)
I'm a bit confused about iframe vs xml vs json vs script-in-script. Wasn't iframe like the devil just two or three years back? Then Google used xml gadgets ubiquitously, just to kill them off (like they do everything else). And json was like, always there - somewhere. And now, iframe - is forgiven, or what is going on I dont even
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/6070/beneidel1.jpg)
I opensourced a small script to do cross-domain requests using a hidden iframe using this same mechanism: https://github.com/benjamine/FrameProxy
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/47533/6b2fed7a920515d34bf4e896ad57e3e4.png)
@skopp sometimes you are forced by your employer to do some stuff they planed months ago ;)