Tuesday, April 17, 2012

Why doesn"t jQuery work in Chrome user scripts (Greasemonkey)?


I'm unable to get this user script to work in Google Chrome.




// ==UserScript==
// @name voip
// @namespace 1
// @description voip
// @include *
// @require http://jquery.com/src/jquery-latest.js
// ==/UserScript==

$(document).ready(function() {
alert("Hello world!");
});



The alert doesn't show up. If I just put alert("Hello world!"); in the script, it works.



How can I use jQuery in Chrome user scripts?


Source: Tips4all

6 comments:

  1. The design document for Chrome's user script's implementation mentions these known issues:



    Chromium does not support @require, @resource, unsafeWindow, GM_registerMenuCommand, GM_setValue, or GM_getValue.
    GM_xmlhttpRequest is same-origin only.



    This is addressed in the question Include Jquery inside GreaseMonkey script under Google Chrome. Here is my answer from that question:



    I have written a few functions based on the script from Erik Vold's answer to help run me run functions, code and other scripts in a document. You can use them to load jQuery into the page, and then run code under the global window scope.

    Example Usage

    // ==UserScript==
    // @name Example from http://stackoverflow.com/q/6825715
    // @version 1.2
    // @namespace http://stackoverflow.com/q/6825715
    // @description An example, adding a border to a post on Stack Overflow.
    // @include http://stackoverflow.com/questions/2588513/*
    // ==/UserScript==

    var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};

    loadAndExecute("//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
    $("#answer-6825715").css("border", ".5em solid black");
    });


    You can click here to install it, if you trust that I'm not trying to trick you into installing something malicious, and that nobody has edited my post to point to something else. Reload the page and you should see a border around my post.

    Functions

    load(url, onLoad, onError)

    Loads the script at url into the document. Optionally, callbacks may be provided for onLoad and onError.

    execute(functionOrCode)

    Inserts a function or string of code into the document and executes it. The functions are converted to source code before being inserted, so they lose their current scope/closures and are run underneath the global window scope.

    loadAndExecute(url, functionOrCode)

    A shortcut; this loads a script from url, then inserts and executes functionOrCode if successful.

    Code

    Source CoffeeScript

    I wrote these in CoffeeScript (a little language that compiles to JavaScript). Here is the CoffeeScript source for use of you are using CofeeScript yourself. For JavaScript users the compiled and minified code is included below.

    load = (url, onLoad, onError) ->
    e = document.createElement "script"
    e.setAttribute "src", url

    if onLoad? then e.addEventListener "load", onLoad
    if onError? then e.addEventListener "error", onError

    document.body.appendChild e

    return e

    execute = (functionOrCode) ->
    if typeof functionOrCode is "function"
    code = "(#{functionOrCode})();"
    else
    code = functionOrCode

    e = document.createElement "script"
    e.textContent = code

    document.body.appendChild e

    return e

    loadAndExecute = (url, functionOrCode) ->
    load url, -> execute functionOrCode


    Compiled and Minified JavaScript (468 characters)

    var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};

    ReplyDelete
  2. This is a nice article: How to play nicely with jQuery and Greasemonkey

    The method explained works for chrome as well.

    Update:

    I came up with a better method that works on all browsers, which you can read about here.

    ReplyDelete
  3. Greasemonkey support in Chrome does not include require statements. You'd be better off creating an extension rather than a Greasemonkey script.

    That, or you could use the Google API to load jQuery.

    ReplyDelete
  4. Easy solution (if viable for you) would be to just copy paste the minified version of jQuery into your greasemonkey script.

    // ==UserScript==
    // @name voip
    // @namespace 1
    // @description voip
    // @include *
    // ==/UserScript==
    //jQuery 1.4.2 minified code
    (function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll...
    ....
    A.jQuery=A.$=c})(window);
    //your code
    $(document).ready(function() {
    alert("Hello world!");
    });

    ReplyDelete
  5. Just create a Chrome Extension using a Content Script. It's quite simple:

    manifest.json

    {
    "name": "Hello World",
    "version": "1.0",
    "description": "Greets the world",
    "content_scripts": [
    {
    "matches": ["*"],
    "css": ["main.css"],
    "js": ["jquery.min.js","main.js"],
    "run at":"document_end",
    }
    ]
    }


    main.js

    $(document).ready(function(){
    alert('Hello World');
    });


    Worth pointing out that in this example, wrapping the alert in $(document).ready() isn't actually necessary, since the manifest file already specifies that the script should be "run at" : "document_end".

    Also, as you'll see in the docs, jquery.min.js and main.js must be included in the same folder as manifest.json

    ReplyDelete
  6. Try using TamperMonkey.

    Your script worked as-is for me and I've made a number of other user scripts that make use of jQuery.

    ReplyDelete