Zhivago
Zhivago

Reputation: 189

Set javascript variable from one iframe to another

Trying pass variable from one iframe to another. Sound weird but I made a picture to make it clear:

image

My first try to add new srcrip to the new iframe. Looks like its work, but new variable undefined.

var creativeFrame = parentDocument.getElementById('iframe2');
var creativeWindow = parentDocument.getElementById('iframe2').contentWindow;
var creativeDocument = creativeFrame.document;

var myFunction = function() {
 var iFrameHead = creativeFrame.document.getElementsByTagName("head")[0];
 var myscript = creativeBody.createElement('script');
 myscript.type = 'text/javascript';
 myscript.text = 'var a = 2';
 iFrameHead.appendChild(myscript);
};
if(creativeFrame.addEventListener) {
 creativeFrame.addEventListener('load', myFunction, true);
} else if(creativeFrame.attachEvent) {
 creativeFrame.attachEvent('onload', myFunction);
}
</script>

Upvotes: 0

Views: 88

Answers (1)

Nino Filiu
Nino Filiu

Reputation: 18493

Window.postMessage() is the recommended way to pass data from one Window object (tab, window, iframe...) to another. Minimal use case:

  1. An event listener must be present in the script of the iframe: window.addEventListener('message', console.log);
  2. The parent window, given a window reference to the iframe, can then send message to the iframe: myIframe.postMessage('hello world', '*')

Upvotes: 1

Related Questions