javascript chrome 选项卡/窗口中的 window.open 行为

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16749907/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:50:37  来源:igfitidea点击:

window.open behaviour in chrome tabs/windows

javascriptgoogle-chromewindow.open

提问by user1151653

I have a small bit of javascript intended to open two or more tabs. This works fine in FF and IE, but chrome opens the second one in a new window instead of tab. It isn't dependant on the url as I've tried it with two identical url's. First opens in tab, second one in new window.

我有一小部分 javascript 旨在打开两个或更多选项卡。这在 FF 和 IE 中工作正常,但 chrome 在新窗口而不是选项卡中打开第二个。它不依赖于 url,因为我已经尝试过使用两个相同的 url。第一个在选项卡中打开,第二个在新窗口中打开。

Here's my code snippet:

这是我的代码片段:

for(var i=0 ; i<sites.length ;i++)
{
    window.open(sites[i].Url);
}

回答by Bagelzone Ha'bonè

Chrome automatically opens a URL in a new tab only if it's user generated action, limited to one tab per user action. In any other case, the URL will be opened in a new window (which, BTW, is blocked by default on Chrome).
window.openmust be called within a callback which is triggered by a user action (e.g. onclick) for the page to open in a new tab instead of a window.

仅当用户生成操作时,Chrome 才会在新标签页中自动打开 URL,每个用户操作仅限于一个标签页。在任何其他情况下,该 URL 将在新窗口中打开(顺便说一句,Chrome 默认情况下会阻止该窗口)。
window.open必须在回调中调用,该回调由用户操作(例如 onclick)触发,以便在新选项卡而不是窗口中打开页面。

In your example, you attempt to open N tabs upon user action. But only the first one is opened in a new tab (because it's a user generated action). Following that, any other URL will be opened in a new window.

在您的示例中,您尝试根据用户操作打开 N 个选项卡。但只有第一个在新选项卡中打开(因为它是用户生成的操作)。之后,任何其他 URL 都将在新窗口中打开。

Similar question: force window.open() to create new tab in chrome(see answer by maclema)

类似问题:强制 window.open() 在 chrome 中创建新选项卡(请参阅 maclema 的回答)

回答by Ganesh G

I came across this question What is the (function() { } )() construct in JavaScript?which gives explanation on IIFE. I think this can be used over. Please bear with me I don't have deep knowledge about javascript. But I tried as below and its working.

我遇到了这个问题 JavaScript 中的 (function() { } )() 构造是什么?它给出了关于 IIFE 的解释。我觉得这个可以用过去。请耐心等待我对javascript没有深入的了解。但我尝试如下并且它的工作原理。

var sites = [{"url" : "http://www.google.com"} , {"url" : "http://www.yahoo.com"} , {"url" : "http://www.msn.com"}];
console.log(sites);
for( var i=0 ; i < sites.length ;i++) {
    (function(i) {
        console.log(i);
        window.open(sites[i].url , "_blank");
    })(i);
}   

It opens the url in new tabs in chrome.

它会在 chrome 的新标签页中打开 url。