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.
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.
For me, the other answers are no sensible option, since some href
s 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"
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With