Search code examples
javascriptjqueryuserscripts

jquery/userscript is not defined?


In chrome my userscript cause the error

ReferenceError: jQuery is not defined

But the line @require includes jquery. At least i know it does with greasemonkey (does chrome not support that?)

If i delete the function that one function call (which makes $ = jQuery) I get the error $ is not defined. In firefox/greasemonkey it runs fine

// ==UserScript==
// @name        Detect Duplicate IDs
// @namespace   jkbfvsdjkzsvfshefsdvh
// @description Alerts you when more than one ID is on a page
// @require     http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js
// @include     *
// @version     1
// @grant
// ==/UserScript==

//using localhost in @include doesn't seem to work
if(location.hostname!='localhost')
    return;

//Ignore above for console.
(function($){
$(function() {
var checkDupeIDs = function () {
    var dupes = [];
    var ids = [];
    $('[id]').each(function(i,e){ids.push(e.id)});
    var len = ids.length;
    for(i=0; i<len; ++i) {
        if(dupes.indexOf(ids[i])!=-1)
            continue;
        for(n=i+1; n<len; ++n) {
            if (ids[n]==ids[i]) {               
                dupes.push(ids[n]);
                break;
            }
        }
    }
    if (dupes.length!=0) { 
        for(i=0; i<dupes.length; ++i)
            console.warn('Multiple IDs #' + dupes[i]);
        alert(dupes.join('\n')); 
    }
}


var jHtml = $.html;
$.html = function () {
    checkDupeIDs();
    return jHtml.call(this, arguments);
}

checkDupeIDs();

})
})(jQuery);

Solution

  • Straight out of the box, Chrome does not support Greasemonkey scripts very well (Out-of-date table, Out-of-date page). The @require directive does not work, for example.

    To enjoy almost complete compatibility for your Firefox Greasemonkey scripts, install the Tampermonkey Extension for Chrome. Your script should work in Tampermonkey.

    Also, to avoid problems in Firefox, do not leave @grant blank. Use @grant  GM_addStyle, if nothing else.