Search code examples
javascriptgreasemonkey

Using a Greasemonkey script to add javascript, from other sites, to a page


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


Solution

  • 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.