Search code examples
javascriptjquerygoogle-chromeuserscripts

How do I access pages jQuery from user script?


I want to write a small userscript to the page that already contains jQuery. I can access $ object from chrome developer console, but can not from user script -- it just says that jQuery || $ || window.jQuery is undefined.

PS: user script is installed as an extension.


Solution

  • Userscripts don't run in the same context as the page. In order to access the page's javascript environment, you need to run it like so:

    var execute = function (body) {
        if(typeof body === "function") { body = "(" + body + ")();"; }
        var el = document.createElement("script");
        el.textContent = body;
        document.body.appendChild(el);
        return el;
    };
    
    execute(function() {
        $.noop();
    }
    

    Bonus: you can also load external scripts from a CDN.

    var load = function (src, on_load, on_error) {
        var el = document.createElement("script");
        el.setAttribute("src", src);
        if (on_load != null) { el.addEventListener("load", on_load); }
        if (on_error != null) { el.addEventListener("error", on_error); }
        document.body.appendChild(el);
        return el;
    };
    load("//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js", function () {
        execute(function(){$.noop();});
    });