[Greasemonkey] Patterns

Mark Pilgrim pilgrim at gmail.com
Tue Apr 12 16:42:56 EDT 2005

Inspired in part by
I scanned through the GM scripts I've written in the past few weeks
and came up with a list of patterns that seem to crop up more than
once.  Are the following code snippets the best way to deal with these
situations?  Any other suggestions?

- configure a GM script to execute on a domain and all subdomains

@include http://*.example.com/*
@include http://example.com/*

- Test for GM features

if (!GM_xmlhttpRequest) { alert('upgrade'); return; }

- Do something for every HTML element

var elements = document.getElementsByTagName("*");
var e, i;
for (e = null; i = 0; (e = elements[i]); i++} { ... }

- Do something for every instance of a specific HTML element

var elements = document.evaluate("//img", document, null,
var e, i;
for (e = null; i = 0; (e = elements.snapshotItem(i)); i++) { ... }

- Insert before an existing element

existingElement.parentNode.insertBefore(newElement, existingElement);

- Insert after an existing element


- Remove an element


- Replace an existing element

existingElement.insertBefore(newElement, existingElement);

- Insert complex HTML with a minimum of DOM fussiness

var div = document.createElement('div');
div.innerHTML = '...';
existingElement.insertBefore(div, existingElement);

- Add custom images

Convert image to data: URI using
http://software.hixie.ch/utilities/cgi/data/data and include directly
in GM script

- Add CSS styles

style = document.createElement("style");
style.type = "text/css";
style.innerHTML = '...';

- Test whether page includes an HTML element

if (document.getElementsByTagName("foo")) { ... }

- Test whether page contains text string

if (document.textContent.indexOf(...) != -1) { ... }

- Post-process page after it renders

window.addEventListener("load", function() { ... }, true);

- Match case-insensitive attribute values

var elements = document.evaluate("//a[translate(@href, 'MATCHTEXT',
'matchtext')]", document, null,

- Get current domain name (possibly including subdomain)

var domain = window.location.href.replace(/^https?:\/\/(.+?)\/.*$/i, '$1');

- Match against multiple regular expressions

Create array of RegExp objects first, c.f.


More information about the Greasemonkey mailing list