I want to be able to send a message from my web app to my chrome extension so it can easier to use (send the auth token so users dont have to login twice). However after looking at the documentation and reading a bunch of SO questions, I cannot get anything working for me.
Here's some parts my manifest.json
:
"content_security_policy": "script-src 'self' https://330218550995.ngrok.io; object-src 'self'",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"externally_connectable": {
"matches": [
"*://localhost/*",
"*://*.ngrok.io/*"
]
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"exclude_matches": [
"*://*.olympiatasks.com/*",
"https://app.olympiatasks.com/*",
"https://*.olympiatasks.com/*"
],
"css": ["/static/css/main.css"],
"js": [
"/static/js/runtime-main.js",
"/static/js/2.js",
"/static/js/main.js"
]
}
],
Inside of the content script
I do this:
const ExtensionID = process.env.REACT_APP_EXTENSION_ID || '';
chrome?.runtime.connect(ExtensionID, { name: 'example' });
chrome?.runtime?.sendMessage('Hi from content script')
Inside of the web page
I do this:
const ExtensionID = process.env.REACT_APP_EXTENSION_ID || "";
chrome.runtime.connect(ExtensionID, { name: "example" });
chrome?.runtime?.sendMessage(ExtensionID, "Hi from app");
Then here is the listener in the background.js
:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log({ request })
});
chrome.runtime.onMessageExternal.addListener((request, sender, sendResponse) => {
console.log("Received message from " + sender + ": ", request);
sendResponse({ received: true }); //respond however you like
});
When I open the website, the extension is successfully injected and in the dev console of the background.js
page I get the following:
Hello world from background.js
{request: "Hi from content script"}
The "hi from app" is missing which means it's not being sent/received. I used ngrok
to setup forwarding to my app thinking that either:
- The domain being
localhost
- The protocol not being
https
could be the problem but as you guess, no luck.
So far I have done the following:
- Setup my
externally_connectable
inside mymanifest.json
- Setup the
onMessageExternal
listener in thebackground.js
- Call
runtime.sendMessage
with the Extension ID like shown in the docs - Used an
https
website for secure connection
Any help on this issue is greatly appreciated
Thanks to @wOxxOm comment I was able to resolve the issue.
I quote:
I changed the URL to use one more specific
https://330218550995.ngrok.io/*
and it now works