crxjs / chrome-extension-tools

Bundling Chrome Extensions can be pretty complex. It doesn't have to be.
https://crxjs.dev/vite-plugin
2.75k stars 182 forks source link

content-script onMessage.addListener doesn't work #747

Closed qingchoulove closed 1 year ago

qingchoulove commented 1 year ago

Build tool

Vite

Where do you see the problem?

Describe the bug

// content/index.ts

chrome.runtime.onMessage.addListener((message) => {
  console.log("message", message);
});

// popup/index.ts

const onClick = () => {
  console.log("click");
  chrome.runtime.sendMessage("hello");
};

<Button onClick={onClick}>notifications</Button>

// defineManifest

    content_scripts: [
    {
      matches: ["http://*/*", "https://*/*"],
      js: ["src/content/index.tsx"],
    },
  ],

Reproduction

Just follow https://crxjs.dev/vite-plugin/concepts/content-scripts and add the message send and listener。

Logs

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

System Info

System:
    OS: macOS 13.4
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 8.21 MB / 16.00 GB
    Shell: 5.9 - /bin/zsh
  Binaries:
    Node: 20.3.1 - /usr/local/bin/node
    Yarn: 1.22.17 - /usr/local/bin/yarn
    npm: 9.6.7 - /usr/local/bin/npm
  Browsers:
    Chrome: 113.0.5672.126
    Safari: 16.5
  npmPackages:
    @crxjs/vite-plugin: ^2.0.0-beta.18 => 2.0.0-beta.18

Severity

annoyance

gary-lo commented 1 year ago

I get the same error log @qingchoulove what does it actually mean?

qingchoulove commented 1 year ago

I get the same error log @qingchoulove what does it actually mean?

When sending messages from background.js or action.js to content.js, you should use chrome.tabs.sendMessage().