[Greasemonkey] Patterns

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


Inspired in part by
<http://www.ldodds.com/projects/patterns/patterns_of_intermediation.html>,
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,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, 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

existingElement.parentNode.insertBefore(newElement,
existingElement.nextSibling);

- Remove an element

existingElement.parentNode.removeChild(existingElement);

- Replace an existing element

existingElement.insertBefore(newElement, existingElement);
existingElement.parentNode.removeChild(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 = '...';
document.getElementsByTagName('head')[0].appendChild(style);

- 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,
XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, 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.
http://diveintomark.org/projects/greasemonkey/dumbquotes.user.js

-- 
Cheers,
-Mark


More information about the Greasemonkey mailing list