hfnm3q
Last Updated: February 25, 2016
·
3.79K
· fayp

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.

4 Responses
Add your response

1557

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

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

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

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

over 1 year ago ·