Is it possible to use a Greasemonkey script to add in JS scripts from other sites to a page, so that they run?
2 Answers
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 useunsafeWindowto 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.
6 Comments
Brock Adams
+1 for
@require. You don't need to wrap this code in an anonymous function.Thomas Ward
Can I repeat using the variable
scriptElement multiple times, to pull in multiple external javascripts? (such as script1.js and script2.js)Thomas Ward
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.
Nemo64
@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.
Thomas Ward
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 |
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
fdrv
it doesnt work if i need load script from http for https
Peter Gerdes
Will this always execute the script? One doesn't need to wait for confirmation of execution before removing the child?