我正在尝试使用thiese两个片段获取所有已打开的标签和所选标签的URL
// For Getting URL of All Opened Tabs
chrome.tabs.getCurrent(function(tabs) {
for (var i = 0; i < tabs.length; i++) {
console.log(tab.url);
}
});
// For Getting URL of Selected Tab
chrome.tabs.getSelected(function(tab) {
console.log(tab.url);
});
但他们都没有工作。要获取所有选项卡,我收到此错误:
对tabs.getCurrent的响应出错:TypeError:无法读取未定义的属性“length”
并获取所选标签
未定义
你可以告诉我为什么会这样,我该如何解决?
答案 0 :(得分:1)
chrome.tabs.getSelected
has been deprecated。所以我们应该使用tabs.query({active: true}...
代替。
chrome.tabs.getCurrent
传递single tab to the callback function。它没有&#34;获取所有已打开标签的网址&#34; ,它:
获取此脚本调用的选项卡。如果从非选项卡上下文调用(例如:后台页面或弹出视图),则可能未定义。
所以:
// Write the URL of the current tab to the console
chrome.tabs.getCurrent(tab => console.log(tab.url));
这需要清单中的"activeTab"
或"tabs"
权限。如果出现错误,则不会抛出异常,而是会填充chrome.runtime.lastError
。
我发现使用异步或承诺包装器库(如chrome-extension-async
)处理所有回调更容易。这样我们就可以使用async
/ await
语法和常规try-catch
:
try {
const currentTab = await chrome.tabs.getCurrent();
console.log(currentTab.url);
}
catch(err) {
// Handle errors
}
在您的popup.html
中,您无法访问chrome.tabs.getCurrent
- 您必须使用chrome.tabs.query
代替:
async function writeAllTabUrlToConsole() {
try {
// Get all the tabs
const tabs = await chrome.tabs.query({});
// Write all their URLs to the popup's console
for(let t of tabs)
console.log(t.url, t.active);
}
catch(err) {
// Handle errors
}
}