我尝试使用以下两个片段获取所有打开的选项卡和选定选项卡的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”
获取所选选项卡:
未定义
为什么会发生这种情况,我该如何解决它?
1条答案
按热度按时间3df52oht1#
chrome.tabs.getSelected
已被弃用。所以我们应该使用tabs.query({active: true}...
来代替。chrome.tabs.getCurrent
将单个制表符传递给回调函数。它不会 “获取所有打开选项卡的URL”,而是:获取从中进行此脚本调用的选项卡。如果从非制表符上下文调用,则可能未定义(例如:背景页面或弹出视图)。
所以:
这需要清单中的
"activeTab"
或"tabs"
权限。如果出现错误,它不会抛出异常,而是填充chrome.runtime.lastError
。我发现使用异步或promise Package 器库(如
chrome-extension-async
)处理所有回调更容易。这让我们使用async
/await
语法和常规的try-catch
:在您的
popup.html
中,您无法访问chrome.tabs.getCurrent
-您必须使用chrome.tabs.query
: