简体   繁体   English

如何在Chrome扩展程序中在后台的邮件侦听器中检索活动选项卡?

[英]How to retrieve the active tab, inside message listener in background, in chrome extension?

I'm using the following code (in background.js ) to get the active tab 我正在使用以下代码(在background.js中 )来获取活动标签

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

This works great, except for one case: when this piece of code is inside a messaging listener. 除一种情况外,此方法非常有效:当这段代码位于消息传递侦听器内部时。 For example the next scenario: 例如下一个场景:

In background.js 在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);
        });
    }
);

*in content_script.js* *在content_script.js中*

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

I only got the following in console 我在控制台中只有以下内容

message received 收到消息

and I didn't get the second log in console. 而且我没有第二次登录控制台。

Why is this happening and how to solve it ? 为什么会发生这种情况以及如何解决?

There is an unclosed parenthesis in your code, which raises an exception and aborts execution. 您的代码中有一个未封闭的括号,这会引发异常并中止执行。 Correct it like this: 像这样更正它:

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 `);`
    }
);

That said, if you just want to get the tab that sent the message, it is much easier: 就是说,如果您只想获取发送消息的选项卡,则要容易得多:

sender.tab.id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM