最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.open behaviour in chrome tabswindows - Stack Overflow

programmeradmin5浏览0评论

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.

Here's my code snippet:

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

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.

Here's my code snippet:

for(var i=0 ; i<sites.length ;i++)
{
    window.open(sites[i].Url);
}
Share Improve this question edited May 26, 2013 at 16:03 Bagelzone Ha'bonè 1,2021 gold badge15 silver badges29 bronze badges asked May 25, 2013 at 13:14 user1151653user1151653 831 gold badge1 silver badge4 bronze badges 4
  • Can you be more clear? I don't understand your question – Niccolò Campolungo Commented May 25, 2013 at 13:16
  • @LightStyle His code opens new windows instead of new tabs in Chrome. – Juan Pablo Rinaldi Commented May 25, 2013 at 13:17
  • Just so it's easier to understand here's a test page: bosmaadvies./chrometest.html – user1151653 Commented May 25, 2013 at 15:47
  • (make sure pop-ups are allowed on that site) – user1151653 Commented May 25, 2013 at 15:57
Add a ment  | 

2 Answers 2

Reset to default 12

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.open must 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.

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.

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

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.

var sites = [{"url" : "http://www.google."} , {"url" : "http://www.yahoo."} , {"url" : "http://www.msn."}];
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.

发布评论

评论列表(0)

  1. 暂无评论