我所做的如下:
我跟踪我打开的标签页
内容脚本:
// connect to the background script
var port = chrome.extension.connect();
后台脚本
// a tab requests connection to the background script
chrome.extension.onConnect.addListener(function(port) {
var tabId = port.sender.tab.id;
console.log('Received request from content script', port);
// add tab when opened
if (channelTabs.indexOf(tabId) == -1) {
channelTabs.push(tabId);
}
// remove when closed/directed to another url
port.onDisconnect.addListener(function() {
channelTabs.splice(channelTabs.indexOf(tabId), 1);
});
});
现在,当某个操作发生时,我可以从后台脚本通知所有已注册的选项卡(即内容脚本):
var notification = { foo: 'bar' };
for(var i = 0, len = channelTabs.length; i < len; i++) {
chrome.tabs.sendMessage(channelTabs[i], notification, function(responseMessage) {
// message coming back from content script
console.log(responseMessage);
});
}
同样,在内容脚本的另一侧,您可以添加这些消息的侦听器:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.foo == 'bar') {
executeStuff();
// if a callback is given:
sendResponse && sendResponse('success');
}
});
这有点傻,因为它在某些地方是多余的。但我最喜欢这种方式,因为你可以把它包裹起来,让它变得更容易一些。
如果您想了解我如何使用它,请参阅我在 GitHub 上的存储库:chrome 扩展通讯器 https://github.com/dan-lee/chrome-extension-communicator.