如何在chrome扩展中检索活动选项卡、后台消息侦听器内部



我正在使用以下代码(在background.js中)来获取活动选项卡

chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
    console.log("active tab retrieved : " + tabs[0].id);
});

这非常有效,只有一种情况除外:当这段代码位于消息侦听器内部时。例如下一个场景:

在background.js中

chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) { 
        console.log("message received");
        chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
            console.log("active tab retrieved : " + tabs[0].id);
        });
    }
);

*在content_script.js*中

chrome.runtime.sendMessage({}, function(response) {});

我只在控制台中得到了以下内容

收到的消息

我没有得到第二个登录控制台。

为什么会发生这种情况以及如何解决

代码中有一个未闭合的括号,它引发异常并中止执行。这样更正:

chrome.runtime.onMessage.addListener(
    function(message, sender, sendResponse) { 
        console.log("message received");
        chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
            console.log("active tab retrieved : " + tabs[0].id);
        });   // <-- add `);`
    }
);

也就是说,如果你只想得到发送消息的标签,那就容易多了:

sender.tab.id