Experiments with Bookmarklets / Favelets

Intro

There's nothing new here, this is just my first time to play around with bookmarklets, also called favelets. The focus of these bookmarklets is javascript debugging.

I've tested this (quickly) on Win2K with the latest versions of Opera, Firebird, and IE. (21Nov03)

Bookmarklets

Click on a link to run it on this page. Save it as a bookmark to run it on other pages.

EvalTextArea (410 bytes) - adds a form with a textarea and a button to the end of the document. Type expressions into the text area and click the button to evaluate them in the context of the current page.

xWalkTree (132 bytes) - defines the function xWalkTree(), which can then be called from the EvalTextArea.

xLoadScript (150 bytes) - defines the function xLoadScript(), which can then be called from the EvalTextArea.

Usage

You can type any Javascript in the textarea and click the button to evaluate it within the context of the current page. Here's a few examples using xWalkTree. Click the EvalTextArea link. Click the xWalkTree link. Now copy one of the following, paste it into the textarea, and click 'Evaluate'.

Example 1

function myVF(n) {
  if (n.tagName == 'P') n.style.border = '1px dotted red';
  else if (n.tagName == 'DIV') n.style.border = '1px dotted blue';
  else if (n.tagName == 'PRE') {
    n.style.color = '#369';
    n.style.background = '#ccc';
  }
}
xWalkTree(document.body, myVF);

Example 2

function myVF(n) {
  var t = n.getAttribute('title');
  if (t && t.length) n.style.border = '2px solid #000';
}
xWalkTree(document.body, myVF);

Example 3

function myVF(n) {
  if (n.tagName == 'H1') n.style.fontSize = '3em';
  else if (n.tagName == 'H2') n.style.fontSize = '2em';
  else if (n.tagName == 'H3') n.style.fontSize = '1em';
}
xWalkTree(document.body, myVF);

Bookmarklets' Source Code

EvalTextArea

function xEvalTA_load()
{
  var f = document.createElement('FORM');
  f.onsubmit = 'return false';
  var t = document.createElement('TEXTAREA');
  t.id='xDebugTA';
  t.name='xDebugTA';
  t.rows='20';
  t.cols='60';
  var b = document.createElement('INPUT');
  b.type = 'button';
  b.value = 'Evaluate';
  b.onclick = function() {eval(this.form.xDebugTA.value);};
  f.appendChild(t);
  f.appendChild(b);
  document.body.appendChild(f);
}
xEvalTA_load();

xWalkTree

/* xWalkTree()
   Perform a preorder traversal
   on the subtree starting at node 'n'
   and pass each Element node to function 'v'.
*/
function xWalkTree(n, v)
{
  if (n) {
    if (n.nodeType == 1) {v(n);}
    for (var c = n.firstChild; c; c = c.nextSibling) {
      xWalkTree(c, v);
    }
  }
}

xLoadScript

function xLoadScript(url)
{
  var s = document.createElement('script');
  s.src = url;
  document.getElementsByTagName('head')[0].appendChild(s);
}

For more DHTML toys visit Cross-Browser.com