How to add a JavaScript function to an entire web page using the Firefox extension

I am developing a Firefox addon. I want to do to add a custom JavaScript function.

i.e.

function foo() {..} 

Thus, all pages can invoke foo without first defining it.

I look from another answer, for example: http://groups.google.com/group/greasemonkey-users/browse_thread/thread/3d82a2e7322c3fce

But this requires a change on the web page. What if maybe I want to introduce the foo function in Google.com? Can this be done?

I can do this using usercript, but I want to use the extension approach, if possible.

+4
source share
3 answers

What if you create a simple href with javascript function on the page.
How 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 url.
It should be only one line of code generated by the url, but for the readability of the code I created.

I never developed a Firefox extension, but for javascript injection, that I would give up. Hope this helps.

+1
source

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

In any case, here is the Jetpack add-in (add-in) that injects a script into each loaded page :

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(); 
+6
source

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); 
+1
source

Source: https://habr.com/ru/post/1391137/


All Articles