防止在新标签/窗口中打开页面 [英] Preventing pages being open in a new tab/window
问题描述
我正在开发一个项目,当用户在新标签页或新窗口中打开页面时,该行为会非常奇怪,从而导致应用程序崩溃。
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.
我需要一些可以帮助我防止这种情况的JavaScript。所以基本上我想阻止ctrl + click,鼠标中键,shift + click,从上下文菜单中打开一个新的选项卡/窗口;或至少阻止尽可能多的。我不想阻止正确的ckick(如果可能的话),因为这绝不是一个解决方案。
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.
注意:我对js很新,所以任何非常感谢帮助。
推荐答案
而不是
<a href="http://stackoverflow.com">link</a>
使用
<a href="javascript:void(0);" onclick="javascript:window.location.href='http://stackoverflow.com';">link</a>
鼠标中键在同一个标签页中打开此位置,右键单击 - > ;在新标签页中打开
打开 about:blank
page。
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]);
}
而不是< 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);
}
这样链接保持不变< a href =...>
,但如果用户禁用了JavaScript,则可以在另一个标签/窗口中打开链接。
this way links stay the same <a href="...">
, but if user has disabled JavaScript, links may be opened in another tab/window.
这篇关于防止在新标签/窗口中打开页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!