-2

我正在尝试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:无法读取未定义的属性“长度”

并获取选定的选项卡

不明确的

你能告诉我为什么会这样吗?我该如何解决?

在此处输入图像描述

4

1 回答 1

2

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"or"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
    }
}
于 2017-03-29T08:48:17.597 回答