问题描述
注意:我发布了这个问题,有人将其标记为 this question 的副本。在那个问题中,解决方案是检查弹出窗口而不是查看普通的开发工具。我的问题不是我不知道去哪里看,而是弹出/后台脚本控制台的行为不像我期望的那样。在我的测试中,chrome.runtime.sendMessage
没有将消息传递给后台脚本。
第一次构建清单 v3 扩展(或任何与此相关的扩展)。
我正在努力跟随Google's Message Passing documentation。在扩展加载时从我的内容脚本向我的后台服务工作者发送消息时,它工作正常。现在我想弄清楚如何从我的 popup.html 向后台服务工作者发送消息。我在这个扩展中使用 React。
content-script.js
console.log("Content script was loaded");
chrome.runtime.sendMessage({ greeting: "hello" },function (response) {
console.log(response.farewell);
});
背景.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;
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"]
}
]
}
当我通过右键单击扩展程序并单击“检查弹出窗口”然后单击 App.js 中的按钮来加载和检查扩展程序后台控制台时,我看到以下控制台日志。
每当我在 App.js 中单击按钮时,我都希望看到“再见”和“单击此按钮”一起记录。
这种行为是否是由于 Service Worker 处于非活动状态?我以为 service worker 上的监听器会触发它恢复活动状态?
我也认为可能是因为我没有将 App.js 添加为内容脚本,所以我也尝试了,但没有成功。
有人知道我如何从 App.js 获取一个按钮来与后台脚本通信吗?
解决方法
我想通了!
我使用的是 chrome 扩展样板库,在 index.js 文件中我找到了一行 serviceWorker.unregister();
。我对此进行了评论,一切都按预期进行。