diff --git a/demo/src/entrypoints/background.ts b/demo/src/entrypoints/background.ts index 5f18ccb3e..8a2a5b819 100644 --- a/demo/src/entrypoints/background.ts +++ b/demo/src/entrypoints/background.ts @@ -7,6 +7,7 @@ export default defineBackground({ console.log(browser.runtime.id); logId(); console.log({ + url: import.meta.url, browser: import.meta.env.BROWSER, chrome: import.meta.env.CHROME, firefox: import.meta.env.FIREFOX, diff --git a/src/core/builders/vite/index.ts b/src/core/builders/vite/index.ts index 79c197df2..940c9da2b 100644 --- a/src/core/builders/vite/index.ts +++ b/src/core/builders/vite/index.ts @@ -63,6 +63,7 @@ export async function createViteBuilder( wxtPlugins.noopBackground(), wxtPlugins.globals(wxtConfig), wxtPlugins.excludeBrowserPolyfill(wxtConfig), + wxtPlugins.defineImportMeta(), ); if (wxtConfig.analysis.enabled) { config.plugins.push(wxtPlugins.bundleAnalysis()); diff --git a/src/core/builders/vite/plugins/defineImportMeta.ts b/src/core/builders/vite/plugins/defineImportMeta.ts new file mode 100644 index 000000000..9d4b9781d --- /dev/null +++ b/src/core/builders/vite/plugins/defineImportMeta.ts @@ -0,0 +1,19 @@ +/** + * Overrides definitions for `import.meta.*` + * + * - `import.meta.url`: Without this, background service workers crash trying to access + * `document.location`, see https://github.com/wxt-dev/wxt/issues/392 + */ +export function defineImportMeta() { + return { + name: 'wxt:define', + config() { + return { + define: { + // This works for all extension contexts, including background service worker + 'import.meta.url': 'self.location.href', + }, + }; + }, + }; +} diff --git a/src/core/builders/vite/plugins/index.ts b/src/core/builders/vite/plugins/index.ts index b5a5da1ee..5f7973be1 100644 --- a/src/core/builders/vite/plugins/index.ts +++ b/src/core/builders/vite/plugins/index.ts @@ -12,3 +12,4 @@ export * from './globals'; export * from './webextensionPolyfillMock'; export * from './excludeBrowserPolyfill'; export * from './entrypointGroupGlobals'; +export * from './defineImportMeta';