Posting message to IFrame from top level HTML document

524 views
Skip to first unread message

Tom Lee

unread,
Jan 25, 2012, 5:47:46 PM1/25/12
to Chromium-extensions
Hi,

I have an IFrame which uses a source HTML page that is within my
chrome extension and I navigate to a page on the web. I am trying to
set up communication between the page and the child IFrame. I have
successfully sent messages to the top level document form the IFrame.
However I cannot send messages from the Main Document to the IFrame. I
am using postMessage and that seems not to work when the target is the
IFrame. So I believe the cross-domain rules are squashing the message.

So does anybody have an idea on how to send a message to the IFrame
from the top level document?

Thanks in advance for any suggestion.

Regards,
Tom

John J Barton

unread,
Jan 30, 2012, 12:43:58 AM1/30/12
to Tom Lee, Chromium-extensions

To be sure I understand your case: you have a web page and in that
page you have an iframe with a src="chrome-extension://<some extension
id>/index.html". Correct?

I do this by the following steps:
In the web app, before the chrome iframe can load:
window.addEventListener('message'...)
Load the chrome frame (I do this by appending the 'iframe' element,
to be sure about order of calls).
In the chrome iframe, in the onload event handler,
window.addEventListener('message', ...
window.parent.postMessage("howdy", "*"); // broadcast howdy
Now we come back to the web-apps 'message' handler. The event we get
will have a 'source' property, that is the window object we use for
return messages back to the iframe.

In practice the code is more complex for two reasons:
1) You should verify that the message event.origin matches your
chrome-extension id to avoid being spoofed by another window,
2) You should target the message from the iframe to the enclosing
domain (event.origin) rather than '*". For this reason I send one
round of "introduction" messages before binding the handlers to the
message processing.

In case it helps, my code is here:
https://github.com/johnjbarton/crx2app
It's more complicated perhaps than you need, FWIW.

jjb

Tom Lee

unread,
Jan 30, 2012, 1:20:12 PM1/30/12
to Chromium-extensions


On Jan 29, 11:43 pm, John J Barton <johnjbar...@johnjbarton.com>
wrote:
Hi John,

Thanks for your message.

I was able to figure out what my issue was from your response. I was
setting (addEventListener) my message handler before the window onload
event was fired in my iframe. That turned out to be the issue.

Thanks for taking time to answer my post.

Regards,
Tom
Reply all
Reply to author
Forward
0 new messages