简体   繁体   English

chrome标签/窗口中的window.open行为

[英]window.open behaviour in chrome tabs/windows

I have a small bit of javascript intended to open two or more tabs. 我有一小部分用于打开两个或更多标签的JavaScript。 This works fine in FF and IE, but chrome opens the second one in a new window instead of tab. 这在FF和IE中工作正常,但chrome在新窗口中打开第二个而不是tab。 It isn't dependant on the url as I've tried it with two identical url's. 它不依赖于url,因为我用两个相同的url尝试了它。 First opens in tab, second one in new window. 首先在选项卡中打开,第二个在新窗口中打开。

Here's my code snippet: 这是我的代码片段:

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

Chrome automatically opens a URL in a new tab only if it's user generated action, limited to one tab per user action. 只有在用户生成的操作时,Chrome才会自动在新标签页中打开网址,每个用户操作仅限一个标签。 In any other case, the URL will be opened in a new window (which, BTW, is blocked by default on Chrome). 在任何其他情况下,URL将在新窗口中打开(BTW,默认情况下在Chrome上被阻止)。
window.open must be called within a callback which is triggered by a user action (eg onclick) for the page to open in a new tab instead of a window. 必须在回调中调用window.open ,该回调由用户操作(例如onclick)触发,以便在新选项卡而不是窗口中打开页面。

In your example, you attempt to open N tabs upon user action. 在您的示例中,您尝试在用户操作时打开N个选项卡。 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. 之后,将在新窗口中打开任何其他URL。

Similar question: force window.open() to create new tab in chrome (see answer by maclema) 类似的问题: 强制window.open()在chrome中创建新选项卡 (请参阅maclema的回答)

I came across this question What is the (function() { } )() construct in JavaScript? 我遇到了这个问题JavaScript中的(function(){})()构造是什么? which gives explanation on IIFE. 其中给出了对IIFE的解释。 I think this can be used over. 我认为这可以用完了。 Please bear with me I don't have deep knowledge about javascript. 请耐心等待我对javascript的了解不多。 But I tried as below and its working. 但我尝试了如下,它的工作。

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的新标签中打开网址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM