Google chrome extension chrome.runtime.sendMessage未运行onClick(清单V3 chrome扩展)

Google chrome extension chrome.runtime.sendMessage未运行onClick(清单V3 chrome扩展),google-chrome-extension,manifest.json,Google Chrome Extension,Manifest.json,注意:我发布了这个问题,有人将它标记为的副本。在这个问题上,解决方案是检查弹出窗口,而不是查看普通的devtools。我的问题不是我不知道去哪里看,而是弹出/后台脚本控制台的行为不像我期望的那样。在我的测试中,chrome.runtime.sendMessage没有向后台脚本传递消息 第一次构建manifestv3扩展(或任何与此相关的扩展) 我正试着跟着你。在扩展加载时,从我的内容脚本向我的后台服务人员发送消息时,它工作正常。现在我正试图弄清楚如何从popup.html向后台服务人员发送消息。

注意:我发布了这个问题,有人将它标记为的副本。在这个问题上,解决方案是检查弹出窗口,而不是查看普通的devtools。我的问题不是我不知道去哪里看,而是弹出/后台脚本控制台的行为不像我期望的那样。在我的测试中,
chrome.runtime.sendMessage
没有向后台脚本传递消息

第一次构建manifestv3扩展(或任何与此相关的扩展)

我正试着跟着你。在扩展加载时,从我的内容脚本向我的后台服务人员发送消息时,它工作正常。现在我正试图弄清楚如何从popup.html向后台服务人员发送消息。我在这个扩展中使用React

content-script.js

console.log("Content script was loaded");
chrome.runtime.sendMessage({ greeting: "hello" }, function (response) {
  console.log(response.farewell);
});
background.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  console.log(
    sender.tab
      ? "from a content script:" + sender.tab.url
      : "from the extension"
  );
  if (request.greeting == "hello") sendResponse({ farewell: "goodbye" });
});
app.js

/*global chrome*/
import React from "react";
import "./App.css";

const onClick = () => {
  console.log("The button was clicked");
  chrome.runtime.sendMessage({ greeting: "hello" }, function (response) {
    console.log(response.farewell);
  });
};

function App() {
  return (
    <div>
      <p>Hello</p>
      <button
        onClick={() => {
          onClick();
        }}
      >
        Click to send message
      </button>
    </div>
  );
}

export default App;
/*全球chrome*/
从“React”导入React;
导入“/App.css”;
const onClick=()=>{
log(“单击了按钮”);
chrome.runtime.sendMessage({问候语:“你好”},函数(响应){
console.log(response.bye);
});
};
函数App(){
返回(
你好

{ onClick(); }} > 单击以发送消息 ); } 导出默认应用程序;
manifest.json

{
  "name": "Chrome Extension Starter Kit",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "index.html"
  },

  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content-script.js"]
    }
  ]
}

{
“名称”:“镀铬扩展启动套件”,
“版本”:“1.0”,
“清单版本”:3,
“行动”:{
“默认弹出窗口”:“index.html”
},
“背景”:{
“服务工人”:“background.js”
},
“内容脚本”:[
{
“匹配项”:[“

每当我点击App.js中的按钮时,我都会看到“再见”和“点击此按钮”一起被记录

这种行为是因为服务人员处于非活动状态吗?我以为服务人员上的侦听器会触发它返回活动状态

我还认为这可能是因为我没有将App.js添加为内容脚本,所以我也尝试了,但没有成功

有人知道我如何从App.js中获得一个按钮来与后台脚本通信吗?

我知道了


我使用的是一个chrome扩展插件boiler plate库,在index.js文件中我发现了一行
serviceWorker.unregister()
。我对此进行了注释,一切正常。

Ping该扩展样板库的作者,并通知他们ManifestV3扩展不应注册或注销服务人员,因为它会自动进行。是的,只需在Github上告诉他们。嗨,我只是想知道您使用的是哪个样板。我正在尝试g在弹出窗口中单击以调用后台消息,但在v3中使用@TheLearningDev时它从来不会触发,这实际上就是我正在使用的!我能够让它工作。您是否尝试过使用chrome.tabs.create(如果在后台使用它,我无法让回调在该消息上触发)在V3中,根据您的答案判断,为了使问题有一个正确的答案,您需要提到外部库,这将使使用该库的其他人更容易找到问题。我肯定仍在学习如何编写一个好的MCVE,现在完全明白了这一点。请记住以后的问题。感谢您的反馈@wOxxOm!