Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

Thanks in advance for help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
589 views
Welcome To Ask or Share your Answers For Others

1 Answer

What about the case where the links are being generated while the page is being used? This occurs frequently with today's more complex front end frameworks.

The proper solution would probably be to put the click event listener on the document. This is because events on elements propagate to their parents and because a link is actually acted upon by the top-most parent.

This will work for all links, whether they are loaded with the page, or generated dynamically on the front end at any point in time.

function interceptClickEvent(e) {
    var href;
    var target = e.target || e.srcElement;
    if (target.tagName === 'A') {
        href = target.getAttribute('href');

        //put your logic here...
        if (true) {

           //tell the browser not to respond to the link click
           e.preventDefault();
        }
    }
}


//listen for link click events at the document level
if (document.addEventListener) {
    document.addEventListener('click', interceptClickEvent);
} else if (document.attachEvent) {
    document.attachEvent('onclick', interceptClickEvent);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...