Skip to content Skip to sidebar Skip to footer

How To Detect If User It Trying To Open A Link In A New Tab?

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. I want to

Solution 1:

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

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

Documentation

Solution 2:

You can detect that using onblur as well

<html><head><script>functionnewTabaction() {
  document.getElementById("demo").innerHTML = "New tab opened!<br><br>refesh this page to recheck ";
}
window.onblur = newTabaction;
</script></head><body><divid="demo">
Open a new tab and then check this page
</div></body></html>

Post a Comment for "How To Detect If User It Trying To Open A Link In A New Tab?"