Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing document's javascript variable from firefox extension

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

like image 339
parserr Avatar asked Jan 20 '10 17:01

parserr


2 Answers

not so hard :)

in extension:

var jso=window.content.document.defaultView.wrappedJSObject;

now you can access any function or global variable in the webpage from the extension:

alert(jso.pagevar);

jso.pagefunction("hey");
like image 35
squeegee Avatar answered Oct 23 '22 06:10

squeegee


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.

like image 152
Nickolay Avatar answered Oct 23 '22 07:10

Nickolay