我正在使用以下代码(在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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句