window.open behaviour in chrome tabs/windows

谁说胖子不能爱 提交于 2019-11-27 09:29:20
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.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.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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!