Created
July 20, 2021 22:33
-
-
Save DashBarkHuss/4da860d395cea57dd502e8978df1c488 to your computer and use it in GitHub Desktop.
Sample Chrome Extension Message Passing Background to Content Script Manifest V3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
// This is the background script for the extension | |
// A listener for when the user clicks on the extension button | |
// chrome.action.onClicked.addListener(buttonClicked); | |
chrome.action.onClicked.addListener(buttonClicked); | |
// Handle that click | |
function buttonClicked(tab) { | |
// Send a message to the active tab | |
console.log("button clicked!"); | |
// Send a message to the tab that is open when button was clicked | |
console.log("sending message"); | |
chrome.tabs.sendMessage(tab.id, { message: "browser action" }); | |
} | |
// Listening for messages | |
chrome.runtime.onMessage.addListener(receiver); | |
function receiver(request, sender, sendResponse) { | |
if (request.message === "thank you") { | |
// Not doing anything for messages received but I could! | |
} | |
} | |
} catch (err) { | |
console.log(err); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" }); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"manifest_version": 3, | |
"version": "1.0", | |
"name": "Manifest 3 first version", | |
"content_scripts": [{ "matches": ["<all_urls>"], "js": ["content.js"] }], | |
"background": { | |
"service_worker": "background.js" | |
}, | |
"action": { "default_icon": "icon.png" } | |
} |
Did someone fix them?
background.js:1 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@FlamedDogo99 , try to inject the listener before you send the message. So, add
run_at
in the content_scripts prop on the manifest file. This should resolve the issue.