我正在制作一个 Chrome 扩展,它会在加载后立即关闭某个网站,并且有一个 content.js 页面和一个 background.js 页面。 background.js 页面正常工作,正在等待来自 content.js 的消息:
chrome.runtime.onMessage.addListener(function(msg, _, sendResponse) {
if (msg.closeTab) {
chrome.tabs.remove(msg.tabID);
}
});
content.js中发送消息的代码是:
addButton("Close this tab.", function() {
chrome.runtime.sendMessage({closeTab: true, tabID: tab.id});
});
但我遇到的问题是 tab
未定义。
我使用按钮只是为了测试功能。
最佳答案
在消息监听器函数中,您可以使用第二个参数来检索调用者的选项卡 ID,但无法从内容脚本中获取选项卡 ID。
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse){
if (msg.closeTab){
chrome.tabs.remove(sender.tab.id)
}
});
content.js 是
addButton("Close this tab", function(){
chrome.runtime.sendMessage({closeTab:true});
});
参见chrome.runtime.onMessage ,尤其是第二个参数sender
。
关于javascript - 如何获取正在运行 content.js 的选项卡的选项卡 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41411298/