Comments: Sending messages from content to chrome (part 3)

Wow, this is useful. I have run into the same situation, but never pursued a solution. Thanks for sharing.

Posted by mawrya at May 25, 2006 7:33 PM

I'm using the following technique for quite some time now:
To generate the event in the webpage:

top.mydata = mydata //can be any object
var event = document.createEvent("Events");
event.initEvent("myevent", true, true);
top.dispatchEvent(event);

To catch the event in chrome:

addEventListener("myevent",onMyEvent,false,true);
function onMyEvent(event) {
var target = event.target.wrappedJSObject;
var mydata = target.mydata;
//....
}

No need for a component

(From Alex: Due to an ancient architectural bug in our software, we couldn't do that. top.mydata would only allow one slot worth of data to be carried; it's not OOP. The solution I came up with is more flexible. On top of that, events are a little expensive on the Mozilla code - there's a lot of nodes which have to process the event, even if only to detect whether the event affects them or not.)

Posted by Peter Leugner at May 26, 2006 1:44 AM

Yeah - this could be really useful. I've needed something like this for a while, but wasn't sure it was possible, so I didn't spend a lot of time trying to figure it out. As a general capability, it could really open up the possibilities for cool extensions that do things with web pages. Firefox really needs something like that to really take off.

Posted by Steve at September 15, 2006 6:48 AM

what a beautiful man you are :)
I had given up being able to send message from content to chrome. I basically had to create a div with a certain ID and on each page load my extension would watch for that id, then assign a certain onclick I needed for it.

Posted by Jim Plush at November 11, 2006 12:40 PM

For people who find this page -and- read the comments, here's the solution I've been recommending for people to use:

http://forums.mozillazine.org/viewtopic.php?p=1005555#1005555

Note that it's slightly different from the solution in comment 2 - it doesn't use wrappedJSObject, so it is generally safer. If you want to pass more complicated structures than just strings, you can pass the JSON representation of those structures.

Posted by Nickolay Ponomarev at February 5, 2007 2:56 PM