hfnm3q
Last Updated: February 25, 2016
·
3.398K
· fayp
6f1c35204babffb4a1afd6fd6a3b542d

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.

Say Thanks
Respond

4 Responses
Add your response

1557
Profile 2015 2

Didn't know about it. It seems to be supported even for IE8+ http://caniuse.com/#feat=x-doc-messaging

over 1 year ago ·
1569
74c714225754481aabee8ab22408cd2d

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

over 1 year ago ·
1604
Beneidel1

I opensourced a small script to do cross-domain requests using a hidden iframe using this same mechanism: https://github.com/benjamine/FrameProxy

over 1 year ago ·
2651
6b2fed7a920515d34bf4e896ad57e3e4

@skopp sometimes you are forced by your employer to do some stuff they planed months ago ;)

over 1 year ago ·