Skip to content

Commit

Permalink
fix: Don't crash background service worker when using `import.meta.ur…
Browse files Browse the repository at this point in the history
…l` (#402)
  • Loading branch information
aklinker1 authored Feb 3, 2024
1 parent 72e3c5b commit 66bd957
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions demo/src/entrypoints/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions src/core/builders/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down
19 changes: 19 additions & 0 deletions src/core/builders/vite/plugins/defineImportMeta.ts
Original file line number Diff line number Diff line change
@@ -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',
},
};
},
};
}
1 change: 1 addition & 0 deletions src/core/builders/vite/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export * from './globals';
export * from './webextensionPolyfillMock';
export * from './excludeBrowserPolyfill';
export * from './entrypointGroupGlobals';
export * from './defineImportMeta';

0 comments on commit 66bd957

Please sign in to comment.