与Chrome扩展的错误,将消息从背景发送到内容脚本

发布于 2025-01-17 16:14:24 字数 1252 浏览 1 评论 0原文

我正在学习有关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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文