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
Replace all < a > tags attribute to _self, that will force the broswer to open the hyperlink in a new tab
Array.prototype.forEach.call(document.getElementsByTagName('a'), function(el, i){
if(el.target=="_blank"){ 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.
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()}
});