I’ve been working on a little Greasemonkey hack recently and learned a few things I wish I knew at the outset:

  • Avoiding common Greasemonkey pitfalls is worth reading. Pitfalls #3 and #4 are helpful reminders that DOM elements like document are wrapped in XPCNativeWrapper objects for Greasemonkey and need to be accessed differently than typical in Javascript code.
  • With ECMAScript for XML (E4X) you can simulate HEREDOC in Javascript which is great when blasting HTML or CSS. Having to escape strings and join multi-line strings is tedious.
    var s = (<r><![CDATA[
                #foo p { color: red; }
                #bar h1 { margin: 0px; }
                ]]></r>).toString();
    
    
    FireFox 2 supports it, so who cares about IE? And that right there -- developing for a single, sane browser -- is the most fun part of GM scripting compared to most JS coding.
  • My script displays some HTML regardless of the site it is run on. Unless you want to allow the underlying site's CSS to apply to your HTML, the best way is to use an iframe to inject HTML. That way when you add CSS rules, those will be the only ones affecting the layout. One trick in conjunction with that is using the "wait" function to make sure the iframe has been truly loaded before manipulating the new iframe.
  • Greasemonkey will run when the DOMContentLoaded event fires. On some AJAX heavy sites like Gmail or ones that include ads via javascript-created iframes like Digg, this can make it seem like your script is being called more than once for a visited URL. The original page can be distinguished from the iframe using:
    // Don't run on iframes
    if(top != self) return;
    
  • Oh, and the Javascript Shell is fantastic for interactively inspecting the DOM (if launched from the FF bookmarklet). Great way to test your code dynamically.
  • Lastly, the forthcoming Greasemonkey 0.8 has at least one killer feature -- "resources". Greasemonkey resources provide the ability to reference external images, css or javascript. I'm sure they must have heard this request a million times. And being able to easily include a JS library like jQuery or images will make GM scripting that much more enjoyable (although data URIs are still cool). </ul>