javascript - 如何获取正在运行 content.js 的选项卡的选项卡 ID?

标签 javascript google-chrome-extension

我正在制作一个 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/

相关文章:

javascript - 如何从数组中删除对象?

javascript - 使用 JavaScript 设置 HTML5 输入列表值

javascript - 操纵 CSS Pseudo::After 属性

Javascript Date 使用 UTC 时间来校正 GMT 时间

javascript - 使用 Chrome 扩展程序向网页添加按钮

javascript - ng-src 无法正常工作

javascript - chrome.runtime.onmessage无法启动

javascript - 是否可以提取用户在pdf中选择的文本?

javascript - Chrome 扩展程序 : callback function not getting called

javascript - 如何在 Google Chrome 扩展程序中使用 HTML5 的 localStorage?