javascripthtmldom-eventscross-browser

Use JavaScript to intercept all document link clicks


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";
  }
} 

Solution

  • 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.