Skip to content

Instantly share code, notes, and snippets.

Created July 20, 2021 22:33
What would you like to do?
Sample Chrome Extension Message Passing Background to Content Script Manifest V3
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);
// 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(, { message: "browser action" });
// Listening for messages
function receiver(request, sender, sendResponse) {
if (request.message === "thank you") {
// Not doing anything for messages received but I could!
} catch (err) {
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
? "from a content script:" +
: "from the extension"
if (request.greeting === "hello") sendResponse({ farewell: "goodbye" });
"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" }
Copy link

DashBarkHuss commented Jul 20, 2021

All go in the root directory.
You can add an icon.png in the root directory. Otherwise it will use a default icon- a blue puzzle piece.

Copy link

rypptc commented Mar 30, 2022

Thank you for sharing your code. I'm trying to understand how to send messages, specially from background to scripts. I tried your code and I got an error:Uncaught (in promise) Error: The message port closed before a response was received.

Copy link

Me too I get the following error:
Uncaught (in promise) Error: The message port closed before a response was received.

Copy link

@FedericoGentile and @rypptc I got that error too. Not sure why. But the extension still works and seems to send the message even with the error.

Copy link

also getting this error message, MV3 seems messy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment