Posts Tagged ‘greasemonkey’

Include jQuery in Greasemonkey – the nice way

Sunday, September 14th, 2008

When someone wants to write a bit more complex javascript with Greasemonkey, the plain getElementsBy functions may not be enough: enter jQuery. But how to include jQuery, without messing up the original document, eg. without causing a leak to the unsafeWindow? Most people include it the old way (using header script inclusion), which is not that nice; here’s what I do (though probably nothing new under the sun):

(function(){

GM_xmlhttpRequest({
method: "GET",
url: "http://jqueryjs.googlecode.com/files/jquery-1.2.6.pack.js",
onload: run
});

function run(details) {

if (details.status != 200) {
GM_log("no jQuery found!");
return;
}

eval(details.responseText);
var $ = jQuery;

//do something useful here....
}

})();

First we bootstrap jQuery using the GM_xmlhttpRequest builtin function (cross-domain ajax from GM) then we evaluate the whole stuff in our little sandbox. Hope someone finds this useful.

Edit: as Tibor noted bellow in the comments there’s a new require tag in Greasemonkey 0.8+, that can be used for the same purpose. Unfortunately no matter how hard I tried it with Firefox 3.0.1 and GM 0.8.2008x this did not work, or at least the provided example did nothing for me.

Overriding css rules with Greasemonkey

Tuesday, September 9th, 2008

With Greasemonkey one can rewrite webpages on the fly: while the possibilities are pretty much infinite, sometimes all I need is a simple css fix (without messing with userchrome).

Most scripts use the addGlobalStyle(css) function (create style tag and attach it to html head), but the Greasemonkey API has a much more convenient way for that: GM_addStyle().

GM_addStyle(
'span.GM_igBkmTags { display: block; padding-bottom: 3px;' +
'border-bottom: 1px dotted silver; text-align: center; }' +
'span.GM_igBkmTags a { padding-right: 10px; outline: 0; }';
);

I have found the dive into Greasemonkey site pretty useful, but their examples are way too outdated; Mozdev has a much better article for GM related functions!