Thursday, November 22, 2007

Greasemonkey tips

Greasemonkey is a great Firefox add-on that allows you to add custom JavaScript to any web page. This simple concept allows you to do extraordinary changes to a web page and you can find a lot of pre-made scripts around. But if you want to do your own scripts, there's a few things that you should know before you start...

Registering events
Let's say you want to catch a button click. Here's how to do it:

var button = document.getElementById(buttonId);
button.addEventListener('click', myFunction, false);

Don't do stuff like button.onclick = "myFunction()" or even button.onclick = myFunction. It won't work.

Accessing element properties
Suppose you want to add some information to a link that you created to use during the onclick event. You must do it with:

lnk.setAttribute("attrName", value);

and fetch it with:

lnk.getAttribute("attrName");

Doing lnk.attrName or lnk["attrName"] will not work, and will return null when you access it.

Parameters in Event Handlers
Let's say you registered an event like mentioned above. The event always receives a MouseEvent argument, so you should declare the function like myFunction(evt). This is important because if you by accident register as an event handler a function that takes a boolean paramenter, like myFunction(flag), flag will always be "true" when called from the event.

Stopping the bubble
Assuming you defined your function like mentioned earlier, myFunction(evt), you can stop the event from bubbling by calling

evt.preventDefault();

Testing functions
Because Firebug is such a great tool to debug your scripts, you may want to check for Grasemonkey functions before you use them. Do it with something like:

if (typeof(GM_getValue) != "undefined")

And you should be able to run the script outside Greasemonkey for easier debugging.

More tips
Well, so far these were the problems I faced! :-) I'll update this as I keep discovering Greasemonkey's idiosyncrasies.
Post a Comment