3

Is it possible to use a Greasemonkey script to add in JS scripts from other sites to a page, so that they run?

1

2 Answers 2

9

You can simply create a script element and add it to the document

// ==UserScript==
// @name       My Fancy New Userscript
// @description  enter something useful
// @match      http://*/*
// ==/UserScript==

(function () {
    var scriptElement = document.createElement( "script" );
    scriptElement.type = "text/javascript";
    scriptElement.src = "url to your script";
    document.body.appendChild( scriptElement );
})();

If you simply want the script to run then this is enough. If its a library like jQuery you want to use in your userscript it gets tricky. There are 2 ways that I'm aware of:

  • One is to use the require tag of greasemonkey.
  • The other one requires the same creation of a script element like shown above but you need to wait for it to load so scriptElement.onload = function () {} is needed and you'd have to use unsafeWindow to access variables from your library then.

I recommend the first method if this is a pure greasemonkey script because only than you script is encapsulated from the site.

Sign up to request clarification or add additional context in comments.

6 Comments

+1 for @require. You don't need to wrap this code in an anonymous function.
Can I repeat using the variable scriptElement multiple times, to pull in multiple external javascripts? (such as script1.js and script2.js)
Also, is there a way to tell if this actually executes and adds this to the site(s)? Since it pulls in a script for me which will pull in live information and data from a remote .js script, and its not, hence my asking.
@Lord Changing the src again means changing the value of the element in the document. I'd create multiple elements with multiple variables just to be safe.
That's what I figured, so i created three elements: scriptElement1, scriptElement2 and scriptElement3 and it all worked. And I figured out why its not pulling in the data - DNS resolution was borked, since I forgot to update the local DNS server information xD
|
0

Yes, you can do this for example:

let script = document.createElement('script');
script.src = "http://example.com/somescript.js";
document.body.appendChild(script);  // execute the script
document.body.removeChild(script);

2 Comments

it doesnt work if i need load script from http for https
Will this always execute the script? One doesn't need to wait for confirmation of execution before removing the child?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.