繁体   English   中英

在 chrome 扩展中,无法从内容脚本向后台脚本发送消息并获得响应

[英]In a chrome extension, can't send a message from the content script to the background script and get a response

请帮我弄清楚为什么没有收到或回复此消息:

content.js 文件:

console.log('running this');
chrome.runtime.sendMessage({
    greeting: 'get-user-data'
}, (response) => {
    // 3. Got an asynchronous response with the data from the service worker
    console.log('received user data', response);
});

背景.js 文件:

console.log('background.js running');
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('Message received: ', message);
    // 2. A page requested user data, respond with a copy of `user`
    if (message.greeting === 'get-user-data') {
        sendResponse(user);
        return true;
    }
    return true;
});

清单.json 文件:

{
  "manifest_version": 3,
  "version": "1.0",
  "action": {
    "default_popup": "index.html"
  },
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": [
        "https://*.myshopify.com/*"
      ],
      "js": [
        "content.js"
      ],
      "run_at": "document_idle"
    }
  ],
  "permissions": [
    "storage",
    "activeTab",
    "tabs",
    "https://*.com/admin/orders/*",
    "scripting",
    "webRequest"
  ]
}

内容脚本中的“running this”控制台日志打印出来,“background.js running”控制台日志也打印出来,但其他控制台日志都没有打印出来。

我已经尝试从扩展文档中复制/粘贴示例,但它不起作用,并询问了每个可用的 AI,但我无法弄清楚为什么它不发送。

我的测试结果与您的说法相矛盾。

在此处输入图像描述

内容.js

console.log('running this');
chrome.runtime.sendMessage({ greeting: 'get-user-data' }, (response) => {
  // 3. Got an asynchronous response with the data from the service worker
  console.log('received user data', response);
});

背景.js

console.log('background.js running');
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Message received: ', message);
  // 2. A page requested user data, respond with a copy of `user`
  if (message.greeting === 'get-user-data') {
    const user = "user";
    sendResponse(user);
    return true;
  }
  return true;
});

清单.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": [
        "https://nory-soft.web.app/*"
      ],
      "js": [
        "content.js"
      ]
    }
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM