[英]Options-enabled content-script Chrome extension without background page?
[英]Chrome Extension: Cannot get background to sendMessage to content-script
这是我的清单:
{
"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);
});
我从来没有记录过任何东西; 我在这里错过了什么?
将此添加到您的清单中
"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 扩展程序,转到一个新页面,这应该开始工作了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.