Search code examples
javascriptgreasemonkey

Can @required scripts clash with other scripts in Greasemonkey?


In Greasemonkey, if a userscript adds things to the global namespace by using e.g. @require react-15.1.0.js, what happens if the original page also included React but an older version (say react-15.0.0.js)? Are the global names kept in separate environments somehow, or is there a possibility that a userscript may break a page (and vice versa) by redefining global names?


Solution

  • No, they cannot clash. I'm not clear on the details of greasemonkey's execution model, but I performed a test. I created this HTML file, which uses lodash when a button is clicked:

    <html>
    <head>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.13.1/lodash.min.js'></script>
    </head>
    <body>
    <input type='button' id="btn" value="Invoke lodash">
    <script type="text/javascript">
    	el = document.getElementById("btn")
    	el.addEventListener('click',function (argument) {
    		console.log("3 =", _.add(1,2));
    	})
    </script>
    </body>
    </html>

    I also created a userscript, which removes _:

    // ==UserScript==
    // @name        Test greasmonkey overriding
    // @namespace   gm-overriding
    // @version     1
    // @grant       none
    // ==/UserScript==
    
    _ = null
    console.log("here is _:", _);

    The userscript does not affect the lodash dependency, and the button click still prints the expected output.