Use JavaScript to intercept all document link clicks

Viewed 28566

How do I intercept link clicks in document? It must be cross-platform.

I am looking for something like this:

// content is a div with innerHTML
var content = document.getElementById("ControlPanelContent");

content.addEventListener("click", ContentClick, false);

 function ContentClick(event) {
 
    if(event.href == "http://oldurl")
  {
     event.href = "http://newurl";
  }
} 
3 Answers
for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
    ls[i].href= "...torture puppies here...";
}

alternatively if you just want to intercept, not change, add an onclick handler. This will get called before navigating to the url:

var handler = function(){
    ...torment kittens here...
}
for (var ls = document.links, numLinks = ls.length, i=0; i<numLinks; i++){
    ls[i].onclick= handler;
}

Note that document.links also contains AREA elements with a href attribute - not just A elements.

Related