2

I am trying to learn how to make Chrome Extensions with the new manifest version 3. My goal is to send a message from background.js to content.js.

I am using the following example that I found online: link to github.

manifest.json

{
  "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" }
}

content.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" });
});

background.js

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);
}

Basically no matter what I do I get the following error in the DevTools:

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

Would you be able to suggest a reason of such behavior and how I could solve it please?

Federico Gentile
  • 5,650
  • 10
  • 47
  • 102
  • When you reload the extension you also need to [reinject the content scripts](https://stackoverflow.com/q/10994324). Also note that content scripts won't run in built-in pages like `chrome://` or `chrome-extension://` or the start tab. – wOxxOm Sep 01 '22 at 09:34
  • @federico have you found any solution? – ankitd Oct 18 '22 at 09:06
  • 1
    @ankitd Finally I changed my goal so not needed to do it anymore. However I created a working example of a plug-in which is I use as template: https://github.com/FedericoGentile/Tab-Time – Federico Gentile Oct 18 '22 at 14:57

0 Answers0