contentscript, dynamic created iframe, postmessage

Posted by thefoyer on Stack Overflow See other posts from Stack Overflow or by thefoyer
Published on 2012-06-29T04:48:51Z Indexed on 2012/06/29 15:16 UTC
Read the original article Hit count: 195

I'm attempting to inject an iframe from a content script. From the content script, post a message to the iframe, without much success. This is the closest I have got. No errors/warnings in the console but it doesn't work (alert test).

contentscript:

var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.com/iframe.php");
iframe.id = "iframe01";
document.getElementsByTagName("body")[0].appendChild(iframe);

//then I inject this "web_accessible_resources" script

var script = document.createElement("script");
script.type = "text/javascript";
script.src = chrome.extension.getURL("postMessage.js");
document.getElementsByTagName("head")[0].appendChild(script);

postMessage.js

window.postMessage({msg: "test"}, "*");

I've also tried

top.postMessage({msg: "test"}, "*");

And

var iframe = document.getElementById('iframe01');
iframe.contentWindow.postMessage({msg: "test"}, "*");

EDIT: I tried to make sure the iframe was loaded before postMessage, even if I put an alert there, it would alert telling me the iframe was loaded.

var iframe = document.getElementById('iframe01');
if (ifrm_prsto.contentWindow.document)
    //do postMessage

EDIT2: I did get it to work by moving the iframe from the contentscript to the inject.js script. Wasn't totally ideal but I do have it working now, I guess.

iframe.php

window.addEventListener("message", function(e) {alert("test");});

I am however able to do the reverse, talk to the parent script from the iframe.

© Stack Overflow or respective owner

Related posts about google-chrome-extension