每当当前标签页的URL发生更改时(无论是通过重新加载还是不重新加载),我都试图从background.js
向content.js
发送一条消息。
在 background.js 中,我为选项卡更新添加了一个侦听器,为当前活动窗口进行了过滤,并发送了一条消息:
/*global chrome*/
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.url) {
chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: "hi"}, function(response) {
console.log(response);
});
});
}
});
在 content.js 中,我添加了onMessage侦听器以检查此消息:
/*global chrome*/
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
console.log("runtime", request);
if (request.message === 'hi') {
console.log('I am from content script: ', request.message);
sendResponse("goodbye");
}
})
但是,这似乎不起作用。当我删除chrome.tabs.onUpdated.addListener
并且只有以下内容时:
chrome.tabs.query({active: true, currentWindow: true},function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {message: "hi"}, function(response) {
console.log(response);
});
});
然后它无论出于什么原因都可以工作。因此,我认为错误在于使用onUpdated侦听器。
谢谢!