rompetoto
rompetoto

Reputation: 23

Generate iframe and communicate via post message issues

Here is my example code I am trying to get working. Although the iframe never writes the received message.

var frame = document.createElement('iframe');
frame.setAttribute('src', 'about:blank');
window.document.body.appendChild(frame);

var frameDoc = frame.contentWindow.document;
frameDoc.body.appendChild(frameDoc.createTextNode('Hi!'));

var code = 'window.addEventListener("message", function(){document.body.innerHTML = "Recieved Message"});';
var loaded = 'window.onload = function(){' + code + '};';
var val = '<scr' + 'ipt type="text/javascript">' + loaded + '</scr' + 'ipt>';

frameDoc.open();
frameDoc.write(val);
frameDoc.close();

setTimeout(function(){
    console.log('posting message...');
    window.postMessage({
    foo: 'bar'
  },'*');
}, 1000);

The goal I am trying to eventually reach is testing iframe communication in JSDOM, but I cannot even get this working in the browser yet.

Anyone have any ideas...?

Upvotes: 0

Views: 900

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42736

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

Syntax

otherWindow.postMessage(message, targetOrigin, [transfer]);

otherWindow

A reference to another window; such a reference may be obtained, for example, using the contentWindow property of an iframe element, the object returned by window.open, or by named or numeric index on window.frames.

You are using the window object of your page, when you need to be using the window object of the target, eg the iframe. Thus, you need to use frame.contentWindow

frame.contentWindow.postMessage({
    foo: 'bar'
},'*');

Upvotes: 1

Related Questions