aklinker1 / vite-plugin-web-extension

Vite plugin for developing Chrome/Web Extensions
https://vite-plugin-web-extension.aklinker1.io/
MIT License
537 stars 46 forks source link

How to use with .svelte files, get error with webextension-polyfill #192

Open steddyman opened 1 month ago

steddyman commented 1 month ago

Using browser / .chrome in .svelte files not working

I am trying to user the chrome.storage api within my .svelte files. I have tried using vite-plugin-web-extension along with the polyfill support described here: https://vite-plugin-web-extension.aklinker1.io/guide/supporting-multiple-browsers.html

In my +page.svelte, I am trying to import this library

    import browser from "webextension-polyfill";

    onMount(() => {
        browser.storage.onChanged.addListener((changes, area) => {
                // console.log('Storage changed:', changes, area);
                if (area === 'sync' && changes.playerName?.newValue) {
                    console.log('Svelte: Player name changed:', changes.playerName.newValue);
                }
            });

But when I do, even though all the configuration has been setup correctly, the above code fails with the following error:

node:internal/event_target:1088
  process.nextTick(() => { throw err; });
                           ^
Error: This script should only be loaded in a browser extension.
    at /Users/stepheneddy/Dropbox/Dev/Crypto/Pixels-Extension/src/node_modules/webextension-polyfill/dist/browser-polyfill.js:23:11
    at /Users/stepheneddy/Dropbox/Dev/Crypto/Pixels-Extension/src/node_modules/webextension-polyfill/dist/browser-polyfill.js:5:5

This is an existing svelte project, I had written my own webpack configuration for to package and build the extension, and I am now switching to using vite-plugin-web-extension because of the need to access chrome.storage.