use javascript to intercept all document link clicks

前端 未结 3 863
深忆病人
深忆病人 2020-12-03 05:13

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          


        
相关标签:
3条回答
  • 2020-12-03 05:38

    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);
    }
    
    0 讨论(0)
  • 2020-12-03 05:49

    I just found this out and it may help some people. In addition to interception, if you want to disallow the link to load another page or reload the current page. Just set the href to '#' (as in internal page ref prefix). Now you can use the link to call a function while staying at the same page.

    0 讨论(0)
  • 2020-12-03 05:54
    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.

    0 讨论(0)
提交回复
热议问题