[英]Opening new tab when clicking on a link in my website keeping the current tab active
I have this code that does what I need. 我有这段代码可以满足我的需求。 It opens the link in another tab but it moves to the newly opened tab leaving the current tab I'm in. I want it to keep my current tab active and newly opened tab just opened.
它会在另一个选项卡中打开链接,但会移动到新打开的选项卡,而使我停留在当前选项卡中。我希望它保持当前选项卡处于活动状态,而新打开的选项卡才刚刚打开。
function loadpopunder() {
var clicked = false;
$('a').each(function() {
this.onclick = function() {
var a = document.createElement("a");
a.href = "http://sitetopopeninnewtab.com";
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
{
a.target = "_blank";
}
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)
{
// var evt = new MouseEvent('click', {'view': window, 'bubbles': true, 'cancelable': true, });
var evt = document.createEvent("MouseEvents");
}
else {
// var evt = new MouseEvent('click', {'view': window, 'bubbles': true, 'cancelable': true, 'metaKey': true, 'ctrlKey': true});
var evt = document.createEvent("MouseEvents");
}
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
if (clicked == false) {
a.dispatchEvent(evt);
clicked = true;
}
}
});
if(window.location.href == 'http://mymainwebsite.com/'){
loadpopunder();
}
This can't be done properly, because you depend on the browser settings. 无法正确完成此操作,因为您取决于浏览器设置。 Even when you open a url in a new tab with
target='_blank'
, if the browser is set to open new pages in a pop-up window, you wont get a new tab. 即使使用
target='_blank'
在新标签页中打开url,如果将浏览器设置为在弹出窗口中打开新页面,也不会获得新标签页。
You should check some other SO answer about it here and here . 您应该在这里和这里检查有关此问题的其他一些答案。
You can see on the comments that all browser have different behaviors. 您可以在评论中看到所有浏览器都有不同的行为。 You can, however, manage new opened windows with javascript
window
object 但是,您可以使用javascript
window
对象管理新打开的窗口
Other thing that you can do, is check if the window is focused or not, by using the javascript visibility api . 您可以做的另一件事是使用javascript 可见性api检查窗口是否聚焦。
Hope that helps. 希望能有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.