与Chrome扩展的错误,将消息从背景发送到内容脚本
我正在学习有关Chrome Extensions的知识,我想将消息从背景发送到内容脚本。我正在尝试做一个最简单的例子,但是我一直遇到以下错误:
事件处理程序中的错误:TypeError:无法读取未定义的属性 (阅读'id') 在sendMessageBackgroundToscript(Chrome-extension://ibghimmhcpdahopejafegpkgfcijmcin/event.js:4:35)
这是代码:
subtest.json:
{
"name": "Send Messages",
"description": "An example of how to send messages from background to script",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "event.js"
},
"action": {
"default_title": "Send Message",
"default_icon": "images/icon32.png"
},
"permissions": [
"scripting"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["script.js"]
}
]
}
event.js:script.js:
chrome.action.onClicked.addListener(sendMessageBackgroundToScript);
function sendMessageBackgroundToScript(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {text: "This is a message"})
}
script.js:script.js:
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message, sender, sendResponse) {
console.log(message.text);
}
I'm learning about Chrome Extensions and I want to send a message from the background to a content script. I'm trying to do the simplest example, but I keep getting the following error:
Error in event handler: TypeError: Cannot read properties of undefined
(reading 'id')
at sendMessageBackgroundToScript (chrome-extension://ibghimmhcpdahopejafegpkgfcijmcin/event.js:4:35)
This is the code:
manifest.json:
{
"name": "Send Messages",
"description": "An example of how to send messages from background to script",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "event.js"
},
"action": {
"default_title": "Send Message",
"default_icon": "images/icon32.png"
},
"permissions": [
"scripting"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["script.js"]
}
]
}
event.js:
chrome.action.onClicked.addListener(sendMessageBackgroundToScript);
function sendMessageBackgroundToScript(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {text: "This is a message"})
}
script.js:
chrome.runtime.onMessage.addListener(gotMessage);
function gotMessage(message, sender, sendResponse) {
console.log(message.text);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论