How to exchange data between iframes

Sometimes it's necessary to be able to send some data (access a variable) across iframes using JavaScript, but due to security restrictions placed by the same origin policy by the browser it is not as easy as using a frame reference with the variable (function) name if the domain name, port or protocol (including http versus https) of the frames do not much. Luckily of are in control of the both frames there are a few methods of passing and accessing data between them depending on the browser and the url.

Frames have the same origin

In this simplest case you can simply call methods of the other frame by obtaining and using reference to it like for example parent.function() in a child frame.

Both frames have the same top level domain (TLD)

If both frames are coming from the same top level domain (for example and you can set JavasScript document.domain property equal to the top domain and from there sending data would be possible:

document.domain = '';

Using postMessage JavaScript method

Recent versions of all browsers all support postMessage method where an arbitrary string can be posted using frame reference.

Check if the browser supports postMessage:

	(typeof window.postMessage == 'undefined')?false:true;

Add event listeners in the receiving frame:

	  window.addEventListener("message", function(){}, false); 
	} else if (window.attachEvent){
		window.attachEvent("message", function(){}, false);

Get reference of the receiving frame and send message from the sending frame:

	window.parent.postMessage( "string", "*" );

The only browser that is still in use and does not provide this functionality is Internet Explorer 7.

Exchanging data using Flash LocalConnection.

For Internet Explorer 7 and earlier sending data between iframes can be accomplished by embedding two swf objects, establishing LocalConnection between them and than using ExternalInterface to send messages from JavaScript to the swfs. LocalConnection data link is restricted to 40k per message, so you might need to chunk your message before sending it and than reassemble it on the receiving side.

Does not seem very simple – watch how a video is streamed using the approach described above.


Please wait...