'Chrome extension Can't send data from backgroud to content

I try to copy some cookies(in text format) to the clipboard. In content_script.js it's not a problem, but when I try to copy something into the clipboard in the background.js it doesn't work because it's not supported. So I decided to send the text from background.js to content_script.js and from there on I can copy it to the clipboard.

I use chrome.tabs.query() and chrome.tabs.sendMessage() to achieve this. Everytime I run my extension I get the following error inside the background console: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

manifest.json:

{
  "name": "Cookies to Desktop",
  "manifest_version": 3,
  "version": "0.0.1",
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "content_script.js"
      ]
    }
  ],
  "background": {
    "service_worker": "background.js"
  },
  "host_permissions": [
    "*://*.google.com/*"
  ],
  "permissions": [
    "cookies",
    "contextMenus",
    "clipboardWrite",
    "tabs"
  ]
}

background.js:

function foo() {
    chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id,
            {
                message: "copyText",
                textToCopy: "some text"
            }, function (response) { })
    })
}

foo()

content_script.js:

chrome.runtime.onMessage.addListener(
    function (textToCopy) {
        console.log('SUCCESS ' + textToCopy)
        alert('SUCCESS')
    }
)

How can I successfully send data from background to content



Sources

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

Source: Stack Overflow

Solution Source