这是我的 list :
{
"name": "my-app",
"version": "0.0.9",
"manifest_version": 2,
"description": "my App",
"content_scripts": [
{
"matches": [
"https://*/*"
],
"js": [
"js/vendors/jquery-3.3.1.min.js",
"js/content.js"
]
}
],
"background": {
"scripts": [
"js/background.js"
]
}
}
这是我的脚本:
// background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
setInterval(() => {
chrome.tabs.sendMessage(tabs[0].id, 'some-message');
}, 3000);
});
// content.js
chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
console.log('in runtime')
console.log(msg);
});
chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
console.log('in extensions')
console.log(msg);
});
我从来没有记录过任何东西;我在这里缺少什么?
最佳答案
将此添加到您的 list 中
"permissions": ["tabs"]
另一个问题是 tabs[0].id。执行该语句后得到的id与浏览器中标签页的实际id不匹配。要实现此功能,请在发生某些事件时执行此函数。我正在让您的 background.js 在 onUpdated 事件发生时发送消息。
chrome.tabs.onUpdated.addListener(function(id, changeInfo, tab){
setInterval(()=>{
chrome.tabs.sendMessage(id, "hellooo from background");
},3000);
});
更新您的 Chrome 扩展程序,转到新页面,这应该开始工作。
关于javascript - Chrome 扩展程序 : Cannot get background to sendMessage to content-script,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54644967/