crxjs / chrome-extension-tools

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

Content scripts not updating in vite #492

Open jonluca opened 2 years ago

jonluca commented 2 years ago

Build tool

Vite

Where do you see the problem?

Describe the bug

I have a script, written in typescript, that is being imported in background.ts with import myScript from "./scripts/content-script?script"; and then run on the page with

  browser.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
    if (tab.url && /somedomain.com/.test(tab.url)) {
      await browser.scripting.executeScript({
        target: { tabId: tab.id },
        files: [myScript],
      });
    }
  });

Any time I edit the content of the file, the file in dist/scripts stays the same, and the file in the Sources > Content Scripts tab stays the same. It's only after a full vite kill + restart and a refresh of the extension that it starts working.

Reproduction

See above, repo unfortunately is not public.

Logs

No response

System Info

System:
    OS: macOS 12.5.1
    CPU: (10) arm64 Apple M1 Max
    Memory: 952.31 MB / 64.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 18.7.0 - /opt/homebrew/bin/node
    Yarn: 1.22.19 - ~/.yarn/bin/yarn
    npm: 8.15.1 - /opt/homebrew/bin/npm
  Browsers:
    Brave Browser: 102.1.39.120
    Chrome: 104.0.5112.101
    Firefox: 103.0
    Safari: 15.6.1
  npmPackages:
    vite: ^3.0.9 => 3.0.9

And a plugin version of    "@vitejs/plugin-react": "^2.0.1"

Severity

annoyance

jonluca commented 2 years ago

Note that it works properly when it's injected via manifest.json

  "content_scripts": [
    {
      "js": ["src/scripts/content-script.ts"],
      "matches": ["*://*/*"]
    }
  ],
jacksteamdev commented 2 years ago

This should be fixed in@crxjs/vite-plugin@2.0.0-beta.1.

ozair-dev commented 2 years ago

I'm currently facing the same issue and it is very annoying, is it being fixed?

jonluca commented 2 years ago

It's fixed for me, is the version installed @crxjs/vite-plugin@2.0.0-beta.4?

ozair-dev commented 2 years ago

Ok I'll check it out, Thanks

logicsb commented 1 year ago

Hi, that's works fine when the world for JS is "ISOLATED" (default). If is set to "MAIN" the loader not works, because the chorme object isn't exists. I think in case of a script injection, the loader is not necessary.

Exemple that fails

import myScript from "./scripts/content-script?script";

browser.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
  if (tab.url && /somedomain.com/.test(tab.url)) {
    await browser.scripting.executeScript({
      target: { tabId: tab.id },
      world: "MAIN",
      files: [myScript],
    });
  }
});