Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing pages being open in a new tab/window

Tags:

javascript

I am working on a project that behaves very strange when the user open pages in a new tab or in a new window, causing the app to crash.

I need some javascript that can help me prevent that. So basically i'd like to block ctrl+click, middle mouse button, shift+click, open in a new tab/window from the context menu; or at least block as many as possible. I wouldn't want to block right ckick(if possible), because that is never a solution.

N.B.: I am very new to js, so any help would be greatly appreciated.

like image 312
Cristian Marian Avatar asked Jul 17 '15 09:07

Cristian Marian


Video Answer


3 Answers

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.

like image 196
Kamil Jarosz Avatar answered Oct 21 '22 11:10

Kamil Jarosz


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()}
});
like image 36
Samuel Vilz Avatar answered Oct 21 '22 10:10

Samuel Vilz


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"
    });
like image 4
Elvin Chu Avatar answered Oct 21 '22 12:10

Elvin Chu