Note: I posted this question and someone marked it as a duplicate of this question. In that question, the solution is to inspect the popup rather than looking in the normal devtools. My issue is not that I don't know where to look, it's that the popup/background script console is not behaving as I would expect it to. In my testing, chrome.runtime.sendMessage
is not passing a message to the background script.
First time building a manifest v3 extension (or any extension for that matter).
I'm trying to follow along with Google's Message Passing documentation. It works fine when sending a message from my content script to my background service worker on extension load. Now I'm trying to figure out how to send messages to the background service worker from my popup.html. I'm using React in this extension.
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;
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"]
}
]
}
When I load and inspect the extension background console by right clicking the extension and clicking "inspect popup" and then click the button from App.js, I see the following console logs.
I would expect to see 'goodbye' logged along with 'This button was clicked' anytime I click the button in App.js.
Is this behavior due to the service worker going inactive? I thought the listeners on the service worker would trigger it to go back to being active?
I also thought it might be because I didn't add App.js as a content-script, so I tried that as well and no luck.
Anyone know how I can get a button from App.js to communicate with the background script?