Reputation: 173
I'm making a Google Chrome extension. I'm trying to open new tabs and group them. I have urls as an array. But chrome.tabs.group function doesn't wait until all tabs open.
var ourTabIds = []
for(const url of urls) {
chrome.tabs.create({active: false, url : url},tab => {
ourTabIds.push(tab.id)
})
}
chrome.tabs.group({tabIds : ourTabIds}, groupId => {console.log(groupId)})
The group function works when the ourTabIds is still empty. So it gives errors.
Why it doesn't wait? How can I fix that?
Upvotes: 1
Views: 123
Reputation: 136174
You could promisify chrome.tabs
and then use Promise.all
function createTab(input){
return new Promise(resolve => {
chrome.tabs.create(input,tab => resolve(tab))
});
}
and then you code becomes
(async function doIt(){
var tabs = await Promise.all(urls.map(url => createTab({active: false, url : url})));
chrome.tabs.group({tabIds : tabs.map(t => t.id)}, groupId => {console.log(groupId)})
})()
Upvotes: 1
Reputation: 1698
The function chrome.tabs.create()
uses a callback as parameter. You should either convert that to Promises and finish it all with .then() or check if it is the last url (changing from of to in)
var ourTabIds = []
for(const index in urls) {
chrome.tabs.create({active: false, url : urls[index]}, tab => {
ourTabIds.push(tab.id)
if (index === urls.length - 1 ) { // last url
//call when EVERYTHING has been pushed by the callback
chrome.tabs.group({tabIds : ourTabIds}, groupId => {console.log(groupId)})
}
})
}
Upvotes: 0
Reputation: 234
var ourTabIds = [];
var countTabs = 0;
for(const url of urls) {
chrome.tabs.create({active: false, url : url},tab => {
ourTabIds.push(tab.id)
countTabs++;
if (countTabs==urls.length){
chrome.tabs.group({tabIds : ourTabIds}, groupId => {console.log(groupId)})
}
})
}
Upvotes: 0