Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hidden features of Greasemonkey [closed]

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:

  • Hidden Features of JavaScript
  • Hidden Features of Java
  • Hidden Features of C++
  • Hidden Features of C#
like image 699
Chris Noe Avatar asked Sep 23 '08 13:09

Chris Noe


2 Answers

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 divs whose class attribute is set to "content".

like image 171
Robert J. Walker Avatar answered Nov 02 '22 02:11

Robert J. Walker


==UserScript==
...
@require http://ajax.googleapis.com/ajax/framework-of-your/choice.js
==/UserScript==
like image 13
mislav Avatar answered Nov 02 '22 01:11

mislav