在Chrome API上获取当前选项卡和所选选项卡URL

jum4pzuy  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(165)

我尝试使用以下两个片段获取所有打开的选项卡和选定选项卡的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”
获取所选选项卡:
未定义
为什么会发生这种情况,我该如何解决它?

3df52oht

3df52oht1#

chrome.tabs.getSelected已被弃用。所以我们应该使用tabs.query({active: true}...来代替。
chrome.tabs.getCurrent将单个制表符传递给回调函数。它不会 “获取所有打开选项卡的URL”,而是:
获取从中进行此脚本调用的选项卡。如果从非制表符上下文调用,则可能未定义(例如:背景页面或弹出视图)。
所以:

// Write the URL of the current tab to the console
chrome.tabs.getCurrent(tab => console.log(tab.url));

这需要清单中的"activeTab""tabs"权限。如果出现错误,它不会抛出异常,而是填充chrome.runtime.lastError
我发现使用异步或promise Package 器库(如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
    }
}

相关问题