Javascript 防止在新选项卡/窗口中打开页面
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31472065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preventing pages being open in a new tab/window
提问by Cristian Marian
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.
我需要一些可以帮助我防止这种情况的 javascript。所以基本上我想阻止 ctrl+click,鼠标中键,shift+click,从上下文菜单中在新选项卡/窗口中打开;或至少阻止尽可能多的人。我不想阻止右 ckick(如果可能),因为那永远不是解决方案。
N.B.: I am very new to js, so any help would be greatly appreciated.
注意:我对 js 很陌生,所以任何帮助将不胜感激。
回答by Kamil Jarosz
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.
单击鼠标中键在同一选项卡中打开此位置,right click -> open in new tab
打开about:blank
页面。
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="...">
.
而不是<a href="...">
使用<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.
这样链接保持不变<a href="...">
,但如果用户禁用了 JavaScript,链接可能会在另一个选项卡/窗口中打开。
回答by Elvin Chu
Replace all < a > tags attribute to _self, that will force the broswer to open the hyperlink in a new tab
将所有 <a> 标签属性替换为 _self,这将强制浏览器在新选项卡中打开超链接
Array.prototype.forEach.call(document.getElementsByTagName('a'), function(el, i){
if(el.target=="_blank"){ el.target="_self" }
});