What are some of the lesser-known but useful features and techniques that people are using in their Greasemonkey scripts?
(Please, just one feature per answer.)
Similar threads:
Greasemonkey scripts often need to search for content on a page. Instead of digging through the DOM, try using XPath to locate nodes of interest. The document.evaluate()
method lets you provide an XPath expression and will return a collection of matching nodes. Here's a nice tutorial to get you started. As an example, here's a script I wrote that causes links in phpBB3 posts to open in a new tab (in the default skin):
// ==UserScript==
// @name New Tab in phpBB3
// @namespace http://robert.walkertribe.com/
// @description Makes links in posts in phpBB3 boards open new tabs.
// ==/UserScript==
var newWin = function(ev) {
var win = window.open(ev.target.href);
if (win) ev.preventDefault();
};
var links = document.evaluate(
"//div[@class='content']//a[not(@onclick) and not(@href='#')]",
document, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var i = 0; i < links.snapshotLength; i++) {
var link = links.snapshotItem(i);
link.addEventListener("click", newWin, true);
}
The XPath expression used in the code identifies all a
elements that 1) do not have an onclick
attribute, 2) whose href
attribute is not set to "#"
, and 3) are found inside div
s whose class
attribute is set to "content"
.
==UserScript==
...
@require http://ajax.googleapis.com/ajax/framework-of-your/choice.js
==/UserScript==
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With