How to detect if user it trying to open a link in a new tab?

前端 未结 2 1172
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 05:08

I\'m writing a website in which all content is stored in the JavaScript environment, so it should be possible to navigate between \"pages\" without additional HTTP requests.

相关标签:
2条回答
  • 2020-12-03 05:20

    You can detect that using onblur as well

    <html>
    <head>
    <script>
    function newTabaction() {
      document.getElementById("demo").innerHTML = "New tab opened!<br><br>refesh this page to recheck ";
    }
    window.onblur = newTabaction;
    </script>
    </head>
    <body>
    <div id="demo">
    Open a new tab and then check this page
    </div>
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-03 05:27

    You can examine the ctrlKey, shiftKey, and metaKey properties of the event object. If either is true, the key control, shift, or meta (Apple's command) key is being held and you should allow the default link action to proceed. Otherwise, you use preventDefault to stop the link action and handle it with javascript instead.

    Add target="_blank" to your anchor markup, so the default link behavior is opening a new tab. Otherwise it will open on top of the current page (that may be desired).

    Here's the javascript, either way:

    document.getElementById("mylink").onclick = function(evnt) {
        if (
            evnt.ctrlKey || 
            evnt.shiftKey || 
            evnt.metaKey || // apple
            (evnt.button && evnt.button == 1) // middle click, >IE9 + everyone else
        ){
            return;
        }
        evnt.preventDefault();
    
        alert("clicked");
        return false;
    }
    

    Fiddle: http://jsfiddle.net/6byrt0wu/

    Documentation

    • MDN Events - https://developer.mozilla.org/en-US/docs/Web/API/Event
    • Event.ctrlKey - https://developer.mozilla.org/en-US/docs/Web/API/event.ctrlKey
    • Event.shiftKey - https://developer.mozilla.org/en-US/docs/Web/API/event.shiftKey
    • Event.metaKey - https://developer.mozilla.org/en-US/docs/Web/API/event.metaKey
    • a tag - https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a
    0 讨论(0)
提交回复
热议问题