Howard
Howard

Reputation: 19805

How to inject a JavaScript function to all web page using Firefox extension

I am developing a Firefox addon. What I want to do is to inject a custom JavaScript function.

i.e.

function foo() {..}

So all the pages can call the foo without define it first.

I have look from other answer such as: http://groups.google.com/group/greasemonkey-users/browse_thread/thread/3d82a2e7322c3fce

But it requires modification on the web page. What if perhaps I want to inject the function foo into Google.com? Is it possible to do so?

I can do it with a userscript, but I want to use the extension approach if possible.

Upvotes: 4

Views: 10017

Answers (3)

Yoann
Yoann

Reputation: 3060

What if you make a simple href with javascript function on the page.
Like bookmarklets work.

Here is a sample code :

function(scriptUrl) {

    var newScript = document.createElement('script');

    // the Math.random() part is for avoiding the cache
    newScript.src = scriptUrl + '?dummy=' + Math.random();

    // append the new script to the dom
    document.body.appendChild(newScript);

    // execute your newly available function
    window.foo();

}('[url of your online script]')


To use it, put your script's url.
It must be only one line of code, url formated, but for code readability I've formated it.

I've never developed a Firefox extension, but for javascript injection that's how I would roll.

Hope it helped.

Upvotes: 2

Reuben Morais
Reuben Morais

Reputation: 1021

The first thing I thought when reading your question was "this looks like a scam". What are you trying to achieve?

Anyway, here's a Jetpack (Add-on builder) add-on that injects a script in every page loaded:

main.js:

const self = require("self"),
      page_mod = require("page-mod");

exports.main = function() {
    page_mod.PageMod({
        include: "*",
        contentScriptWhen: "ready",
        contentScriptFile: self.data.url("inject.js")
    });
};

inject.js:

unsafeWindow.foo = function() {
    alert('hi');
}

unsafeWindow.foo();

Upvotes: 5

Pin Zhang
Pin Zhang

Reputation: 300

You can use Sandbox

// Define DOMContentLoaded event listener in the overlay.js
document.getElementById("appcontent").addEventListener("DOMContentLoaded", function(evt) {
    if (!evt.originalTarget instanceof HTMLDocument) {
        return;
    }

    var view = evt.originalTarget.defaultView;
    if (!view) {
        return;
    }

    var sandbox = new Components.utils.Sandbox(view);
    sandbox.unsafeWindow = view.window.wrappedJSObject;
    sandbox.window = view.window;
    sandbox.document = sandbox.window.document;
    sandbox.__proto__ = sandbox.window;

    // Eval your JS in the sandbox
    Components.utils.evalInSandbox("function foo() {..}", sandbox); 
}, false);

Upvotes: 1

Related Questions