0

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.

yktv4
  • 23
  • 7
  • possible duplicate of [Access an existing copy of jQuery on the target page](http://stackoverflow.com/questions/9871019/access-an-existing-copy-of-jquery-on-the-target-page) – Brock Adams Feb 15 '13 at 19:13
  • see also: http://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script/9517879#9517879 -- the top answer to that question should be the canonical answer to these types of questions. – forivall Feb 19 '13 at 20:07

2 Answers2

3

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();});
});
forivall
  • 9,504
  • 2
  • 33
  • 58
1

You have to include jQuery in the Userscript itself, it doesn't matter if the page has it or not.

Update: My good man Brock (thanks for the heads up!) informs me that the previous link wasn't useful for Chrome extensions, so I found a few other links informing you how to include jQuery for Chrome (you have to add it in the manifest.json file)

Jquery in Chrome Extension
http://blog.michael-forster.de/2009/08/using-jquery-to-build-google-chrome.html

And more info about the manifest.json
http://developer.chrome.com/extensions/manifest.html

  • This is the smart approach (don't rely on the page's jQuery) but that link doesn't apply to Chrome userscripts. In this case, since the OP says that it's installed as an extension, he can include jQuery via the `manifest.json`. – Brock Adams Feb 15 '13 at 19:18
  • I removed the old link Brock is referring to because I couldn't save my edit due to rep issues. Here is the link that Brock is referring to if interested [link](http://wiki.greasespot.net/Third-Party_Libraries#jQuery) – Brian Fitzpatrick Feb 15 '13 at 20:45