在 chrome.tabs.group() 中添加多个选项卡

Add multiple tabs inside chrome.tabs.group()

我无法使用数组在一个组选项卡中添加多个选项卡,因为它 return 这个错误: Uncaught TypeError

这是我的代码:

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);
}
});

我觉得可能是数组内部数据类型的问题,但是我不知道怎么解决,所以请大家帮忙。

chrome API return Promise 或使用回调的方法是异步的,因此结果是 return 在当前同步函数完成后编辑。

您需要将函数声明为 async 并在每次调用时使用 await

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, {...});
});

wOxxOm 非常感谢,这是我完整的工作代码,以备不时之需:

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]
  });
});

这里我仍然使用经典的for循环,因为我数组中的最后一个索引不是URL,所以我需要在最后一个之前停止循环。 这就是我使用 .length - 1.

的原因

但是如果它是 URL 它会像 wOxxOm 写的那样完美地工作:-)