[Greasemonkey] Overlays

Edward Lee edilee at gmail.com
Thu Apr 14 12:40:00 EDT 2005


Not quite what Aaron was talking about.. It does add more
functionality, but it's not quite as easy (for the user script writer)
as a plain html overlay. It requires the creation of nodes in a
callback function, but a container node could easily be made and then
innerHTML could be set.

// path: xpath to select the nodes
// callback: gets passed the current node and should return a new node
// type: select where to place the callback returned node or just visit the node
function overlay(path, callback, type) {
  var items = document.evaluate(path, document, null,
XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  var doIt;

  switch (type) {
  case "before":
    doIt = function(item) {
      item.parentNode.insertBefore(callback(item), item);
    }
    break;
  case "after":
    doIt = function(item) {
      item.parentNode.insertBefore(callback(item), item.nextSibling);
    }
    break;
  case "replace":
    doIt = function(item) {
      item.parentNode.replaceChild(callback(item), item);
    }
    break;
  default: // visit
    doIt = function(item) {
      callback(item);
    }
    break;
  }

  for (var i = 0, ii = null; ii = items.snapshotItem(i); i++) {
    try { // doIt can fail if callback doesn't return a valid node
      doIt(ii);
    } catch(e) {}
  }
}

Example:
// Insert [domain] after all links leading out of the current domain
overlay('//a', function(a) {
  try { // incase the match fails
    var tmp = a.href.match(/:\/\/([^\/]+)/)[1];
    if (tmp != document.location.host) {
      return document.createTextNode(' [' + tmp + ']');
    }
  } catch(e) {}
},'after');

-- 
Ed


More information about the Greasemonkey mailing list