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

Unable to use chrome APIs inside content script #699

Closed paularah closed 1 year ago

paularah commented 1 year ago

Build tool

Vite

Where do you see the problem?

Describe the bug

Chrome is always undefined inside the content script, so I cannot use any Chrome extension APIs. This is straight from the example in the docs. Maybe I might be missing something?

Reproduction

https://github.com/paularah/crjs

Logs

Uncaught TypeError: Cannot read properties of undefined (reading 'getURL')
    at App (App.jsx? [sm]:17:33)
    at renderWithHooks (react-dom.development.js:16305:18)
    at mountIndeterminateComponent (react-dom.development.js:20074:13)
    at beginWork (react-dom.development.js:21587:16)
    at HTMLUnknownElement.callCallback2 (react-dom.development.js:4164:14)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4213:16)
    at invokeGuardedCallback (react-dom.development.js:4277:31)
    at beginWork$1 (react-dom.development.js:27451:7)
    at performUnitOfWork (react-dom.development.js:26557:12)
    at workLoopSync (react-dom.development.js:26466:5)

System Info

System:
    OS: Linux 6.0 Pop!_OS 22.04 LTS
    CPU: (6) x64 AMD Ryzen 5 4500U with Radeon Graphics
    Memory: 2.66 GB / 15.00 GB
    Container: Yes
    Shell: 5.1.16 - /bin/bash
  Binaries:
    Node: 16.20.0 - ~/.volta/tools/image/node/16.20.0/bin/node
    Yarn: 4.0.0-rc.42 - ~/.volta/tools/image/yarn/4.0.0-rc.42/bin/yarn
    npm: 9.6.5 - ~/work/asker/node_modules/.bin/npm
  Browsers:
    Brave Browser: 108.1.46.144
    Chrome: 112.0.5615.49
    Firefox: 106.0.1
  npmPackages:
    @crxjs/vite-plugin: ^2.0.0-beta.16 => 2.0.0-beta.16 
    vite: ^4.3.2 => 4.3.4

Severity

blocking all usage of RPCE

paularah commented 1 year ago

Putting /*global chrome*/ at the beginning of the file temporarily resolves this. But this should be baked into the project by default.

jacksteamdev commented 1 year ago

If /*global chrome*/ fixes it, this is an ESLint error, and not a browser error. Try adding webextensions:true to .eslintrc.cjs:

{
  env: { browser: true, es2020: true, webextensions: true },
  // rest of config...
}
paularah commented 1 year ago

Thanks 🙏