views:

471

answers:

1

is it possible for Firefox extension (toolbar) to access document's variables? detailed explanation follows..

loaded document:

<script type="text/javascript">
var variableForExtension = 'something';
</script>

extension:

var win = window.top.getBrowser().selectedBrowser.contentWindow;
alert(win.variableForExtension); // undefined

it was first thing to try, and it's inaccessible this way because of security mechanisms (XPCNativeWrapper). i've read about accessing it trough wrappedJSObject and using events (adding listener to document and dispatching event from extension), but no luck. didn't try too hard, though. so, before i dig deeper ('events method' sounds like a way to go) i'd like to know is this even possible?

thanks

+4  A: 

Yes, accessing a JS variable in content is and always was possible. Doing this the naive way wasn't safe (in the sense that a malicious web page could get chrome privileges) in older Firefox versions.

1) If you control the web page and want to pass information to the extension, you should indeed use the events technique. This worked and was/is safe in all Firefox versions.

2) If you want to read a value from the content document, you can just bypass the XPCNativeWrapper:

var win = window.top.getBrowser().selectedBrowser.contentWindow;
// By the way, this could just be
//   var win = content;
// or 
//   var win = gBrowser.contentWindow;
alert(win.variableForExtension); // undefined
win.wrappedJSObject.variableForExtension // voila!

This was unsafe prior to Firefox 3. In Firefox 3 and later it is OK to use, you get another kind of wrapper (XPCSafeJSObjectWrapper), which looks the same as the object from the content page to your code, but ensures the content page won't be able to do anything malicious.

3) If you need to call a function in a content web page or run your own code in the page's context, it's more complicated. It was asked and answered elsewhere many times, but unfortunately never documented fully. Since this is unrelated to your question, I won't go into the details.

Nickolay
thanks for answering, nickolay. :) i've done the job in a bit dirty way, but will try (again) both 1 and 2 (i don't need 3, yet), now that i know it's possible.
parserr