Add multiple tabs inside chrome.tabs.group()

1.6k views Asked by At

I cannot add multiple tabs inside one group tab with an array because it return this error : Uncaught TypeError

Here's my code :

for (let group in result) {
//creating the group title and displaying it in the popup
let groupTitle = document.createElement("p");

groupTitle.style.setProperty(
  "--color",
  result[group][result[group].length - 1]
);
groupTitle.classList.add("groupTitle");

let tabsIds = [];
//opening the new tab when the text is click
groupTitle.addEventListener("click", () => {
  for (let i = 0; i < result[group].length - 1; i++) {
    //creating the new tabs one by one
    chrome.tabs.create({ url: result[group][i] }, async function (newTab) {
      tabsIds.push(newTab.id);
    });
  }
  
  //creating a group tab with the tab created
  let groupId = chrome.tabs.group({ tabIds: tabsIds });
  //modifying the group tab
  chrome.tabGroups.update(groupId, {
    collapsed: false,
    title: group,
    color: result[group][result[group].length - 1]
  });
});
groupsContainer.appendChild(groupTitle);
groupTitle.append(group);
}
});

I think it could come from the data types inside the array but I have no clue on how to solve it, so please I beg for your help.

2

There are 2 answers

0
wOxxOm On BEST ANSWER

chrome API methods that return a Promise or use a callback are asynchronous, so the result is returned after the current synchronous function completes.

You need to declare the function as async and use await on every call:

groupTitle.addEventListener('click', async () => {
  const tabsIds = [];
  for (const url of result[group]) {
    const tab = await chrome.tabs.create({url});
    tabsIds.push(tab.id);
  }
  const groupId = await chrome.tabs.group({tabIds: tabsIds});
  //chrome.tabGroups.update(groupId, {...});
});
0
Eli-ott On

wOxxOm thanks a lot, here's my complete and working code in case somebody need it :

groupTitle.addEventListener("click", async () => {
  for (let i = 0; i < result[group].length - 1; i++) {
    //creating the new tabs one by one
    let tab = await chrome.tabs.create({ url: result[group][i] });
    tabsIds.push(tab.id);
  }
  
  //creating a group tab with the tab created
  let groupId = await chrome.tabs.group({ tabIds: tabsIds });
  //modifying the group tab
  await chrome.tabGroups.update(groupId, {
    collapsed: false,
    title: group,
    color: result[group][result[group].length - 1]
  });
});

Here I still use a classic for loop because the last index in my array is not a URL, so I need to stop the loop before the last one. That's why I used .length - 1.

But if it was a URL it'll work perfectly as wOxxOm write it :-)