Preventing pages being open in a new tab/window

For me, the other answers are no sensible option, since some hrefs in my document are procedurally changed. This block of code works though:

document.documentElement.addEventListener('click', function (event) {
  if(event.ctrlKey){event.preventDefault()}
});

Replace all < a > tags attribute to _self, that will force the browser NOT to open the hyperlink in a new tab

2021 UPDATE:

[...document.querySelectorAll('a')].forEach((el) => {
            el.target = "_self"
    });

Instead of

<a href="http://stackoverflow.com">link</a>

use

<a href="javascript:void(0);" onclick="javascript:window.location.href='http://stackoverflow.com';">link</a>

Middle mouse click opens this location in the same tab, right click -> open in new tab opens about:blank page.


When you can't edit every link manually you can use this script:

for(var els = document.getElementsByTagName('a'), i = els.length; i--;){
    els[i].href = 'javascript:void(0);';
    els[i].onclick = (function(el){
        return function(){
            window.location.href = el.getAttribute('data-href');
        };
    })(els[i]);
}

and instead of <a href="..."> use <a data-href="...">.


Going further, you may change script above to following:

for(var els = document.getElementsByTagName('a'), i = els.length; i--;){
    var href = els[i].href;
    els[i].href = 'javascript:void(0);';
    els[i].onclick = (function(el, href){
        return function(){
            window.location.href = href;
        };
    })(els[i], href);
}

this way links stay the same <a href="...">, but if user has disabled JavaScript, links may be opened in another tab/window.

Tags:

Javascript