Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute a page-defined JavaScript function from a Firefox extension?

I'm creating a Firefox extension for demo purposes. I to call a specific JavaScript function in the document from the extension. I wrote this in my HTML document (not inside extension, but a page that is loaded by Firefox):

document.funcToBeCalled = function() {
   // function body
};

Then, the extension will run this on some event:

var document = Application.activeWindow.activeTab.document;
document.funcToBeCalled();

However it raises an error saying that funcToBeCalled is not defined.

Note: I could get an element on the document by calling document.getElementById(id);

like image 820
Randy Sugianto 'Yuku' Avatar asked Sep 30 '08 02:09

Randy Sugianto 'Yuku'


2 Answers

It is for security reasons that you have limited access to the content page from extension. See XPCNativeWrapper and Safely accessing content DOM from chrome,

If you control the page, the best way to do this is set up an event listener in the page and dispatch an event from your extension (addEventListener in the page, dispatchEvent in the extension).

Otherwise, see http://groups.google.com/group/mozilla.dev.extensions/msg/bdf1de5fb305d365

like image 58
Nickolay Avatar answered Sep 21 '22 17:09

Nickolay


document.wrappedJSObject.funcToBeCalled();

This is not secure and allows a malicious page to elevate its permissions to those of your extension... But, it does do what you asked. Read up on the early greasemonkey vulnerabilities for why this is a bad idea.

like image 42
Carlos Rendon Avatar answered Sep 17 '22 17:09

Carlos Rendon