Home require jQuery to a safe variable in Tampermonkey script and console
Reply: 0

require jQuery to a safe variable in Tampermonkey script and console

user2318
1#
user2318 Published in June 20, 2018, 7:37 am

Normally I have used the following code snippet, and this usually works:

(function () {
    function main() {
        //...script body...
    }

    var OGloboCSS = { // var could be named anything, appropriate to the page
        addJQuery: function (callback) {
            var script = document.createElement("script");
            script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js");
            script.addEventListener('load', function () {
                var script = document.createElement("script");
                script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
                document.body.appendChild(script);
            }, false);
            document.body.appendChild(script);
        }
    };

    OGloboCSS.addJQuery(main);

})();

But occasionally I get an error like this one on https://steamcommunity.com:

Refused to load the script 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js' because it violates the following Content Security Policy directive: "script-src 'unsafe-eval' 'self' 'unsafe-inline' 'unsafe-eval' https://steamcommunity-a.akamaihd.net/ https://api.steampowered.com/ http://www.google-analytics.com https://ssl.google-analytics.com https://www.google.com https://www.gstatic.com https://apis.google.com".

And the solution is basically, you have to use TamperMonkey's @require header directive instead, something like this:

// @require      https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// ==/UserScript==

window.jQ = $;

(function () {
/*this used to be: function main() */
    //...same script body, without container function...

})();

And this works just fine, but it doesn't safely load jQuery to the jQ variable, it clobbers $. Is it really a problem? Yes, you can see that in how pagination breaks in steamcommunity.com's discussion threads.

Is there some way to @require jQ= and then @grant jQ - still giving me jQ both in the Tampermonkey script and the console, without clobbering in-page variables?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.366254 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO