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

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

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

Thanks in advance for help.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...