Link Interception Demo

Description

This demonstrates a very cross-browser technique for intercepting all links without adding anything to the HTML. We simply add our own click event listener to all links. When the link is clicked our listener can look at any of the link's properties and then decide to...

  • Replace the URL with a different one.
  • Replace the window target.
  • Disable the link.
  • Cause a visual change (change the link's background, etc.).
  • Ask the user if the link should be followed.
  • Open the link in a specific child window.
  • ... there is no limit to what you can do :-)

This demo does not use the X library.

Tested on Win2K with Opera 7.23, Mozilla 1.6, IE 4, 5, 6, and Navigator 4.8.

Demo

HTML Source

<p><a href='page1'>link1: allows default action</a></p>
<p><a href='page2'>link2: gives option to cancel</a></p>
<p><a href='page3?p=333'>link3: href gets changed</a></p>
<p><a href='page4?p=444'>link4: click gets canceled</a></p>
<p><a href='http://mfoster.com/'>link5: gets opened in new window</a></p>

Javascript Source

window.onload = function()
{
  var lnks = document.links;
  if (lnks) {
    for (var i = 0; i < lnks.length; ++i) {
      lnks[i].onclick = linkOnClick;
    }
  }
}

// These are simple examples. If there is something specific
// you'd like to see done, just let me know.

function linkOnClick()
{
  var h = this.href;
  var action = true;
  
  if (h.indexOf('page1') != -1)               // Link 1
  {
    // allow default action
  }
  else if (h.indexOf('page2') != -1)          // Link 2
  {
    if (!confirm('Do you want to visit the following page?\n\n' + h))
    {
      action = false;
    }
  }
  else if (h.indexOf('p=333') != -1)          // Link 3
  {
    // change href then allow default action
    this.href = 'aDifferentPage';
  }
  else if (h.indexOf('aDifferentPage') != -1) // Link 3
  {
    // change href then allow default action
    this.href = 'page3?p=333';
  }
  else if (h.indexOf('p=444') != -1)          // Link 4
  {
    action = false;
  }
  else if (h.indexOf('mfoster.com') == -1)   // Link 5
  {
    window.open(h);
    action = false;
  }
  return action; // allow or cancel default action
}

Tech Support

Forum support is available at the X Library Support Forums.

License

By your use of X and/or CBE and/or any Javascript from this site you consent to the GNU LGPL - please read it. If you have any questions about the license, read the FAQ and/or come to the forums.