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

There are plenty of issues open on the subject, but I couldn't find an explanation in my case. Here is a minimal test case:

Here is my manifest.json

{
  "manifest_version": 3,
  "name": "Test",
  "version": "1.0",
  "description": "Test extension",
  "icons": {
    "48": "dark.png"
  },
  "background": {
    "service_worker": "button.js"
  },
  "permissions": [
    "activeTab"
  ],
  "action": {
    "default_icon": "dark.png",
    "default_title": "DarkTheme"
  },
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "dark.js"
      ]
    }
  ]
}

button.js

chrome.action.onClicked.addListener(tab => {
  console.log('clicked')
  chrome.tabs.sendMessage(tab.id, { value: false })
});

dark.js

chrome.runtime.onMessage.addListener(request => {
  console.log('received', request)
})

So, basically, my listener is set right at the start, and only when I press the button do I send a message. How come I can receive this error when I press the button?

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

Tested on Chromium Version 100.0.4896.75 (Build officiel) snap (64 bits)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source