我無法在一個帶有陣列的組選項卡中添加多個選項卡,因為它回傳此錯誤: 未捕獲的 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);
}
});
我認為它可能來自陣列中的資料型別,但我不知道如何解決它,所以請大家幫忙。
uj5u.com熱心網友回復:
chrome回傳 Promise 或使用回呼的 API 方法是異步的,因此在當前同步函式完成后回傳結果。
您需要將函式宣告為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, {...});
});
uj5u.com熱心網友回復:
@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]
});
});
這并不完美,我可以做得更好,但這是有效的,我不想破壞一切??
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/463804.html
標籤:javascript 数组 谷歌浏览器扩展 复杂数据类型
