2016-12-31 115 views
0

我正在制作一个Chrome扩展,它在加载后立即关闭某个网站,并且有一个content.js页面和一个background.js页面。该background.js页的工作,并等待来自content.js消息:如何获得运行content.js的选项卡的选项卡ID?

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是未定义的。 我正在使用一个按钮来测试功能。

回答

2

在您的消息监听器函数中,可以使用第二个参数来检索调用者的选项卡标识,但不能从内容脚本中获取选项卡标识。

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

+0

'_'究竟代表什么? – doominabox1

相关问题