0

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>
1
  • yoi can do stuff like iframe.contentWindow.property="test" outside and in the iframe window.property to retrieve it but I want to urge you to think twice about implementing this since an iframe is supposed to always be able to live on its own Commented Apr 1, 2019 at 21:17

1 Answer 1

1

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', '*')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.