Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing injected Javascript code in a page when developing a Firefox extension

I'm developing a Firefox extension which places a button in the status bar. When the button is clicked, the extension injects some Javascript into the current page. This Javascript has a function that I would like to invoke with some parameters. I've managed injecting the code, I've inspected the page through Firebug and verified that the JS has been injected. How can I call a Javascript function in the page from my extension?

--More information

Here's the code that I'm using to inject my Javascript:

var doc = window.content.document;

//Add the script
var visibilityJS = doc.createElement("script");
visibilityJS.setAttribute("type", "text/javascript");
visibilityJS.setAttribute("charset", "UTF-8");
visibilityJS.setAttribute("src", "chrome://visibility/content/scripts/visibility.js");
head.appendChild(visibilityJS);

//Call the function
alert("Executing testfunction");
window.content.document.defaultView.testFunction();

..and the code inside my JS file that i'm going to inject. i.e. visibility.js

window.testFunction = function() {
    alert("Message");
}

Thanks.

like image 503
Mridang Agarwalla Avatar asked Jun 04 '26 20:06

Mridang Agarwalla


2 Answers

This worked. I don't know the technicalities. I got part of the solution from Felix and part of it from here.

window.content.document.defaultView.wrappedJSObject.testFunction();
like image 120
Mridang Agarwalla Avatar answered Jun 06 '26 11:06

Mridang Agarwalla


If you declare a global variable in your injected code (or explicitly set a property of the window object), then one way do get a reference to this element from your extension, is via the gBrowser object:

gBrowser.contentDocument.defaultView.yourObject
          ^-- HTML document  ^
              object         |-- window object

Be careful though, when you use window and document inside your code. Depending on the context it might refer to the Firefox window or the website window object.

like image 34
Felix Kling Avatar answered Jun 06 '26 09:06

Felix Kling