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

非 Y 不嫁゛ 提交于 2020-01-01 03:41:11

问题


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.


回答1:


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.




回答2:


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();



回答3:


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);


来源:https://stackoverflow.com/questions/8872152/how-to-inject-a-javascript-function-to-all-web-page-using-firefox-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!