Skip to content

Commit 3ef5496

Browse files
committed
fix: improve background script detection for MV2/MV3 wxt and non-wxt projects
1 parent aaaff43 commit 3ef5496

File tree

1 file changed

+32
-4
lines changed
  • packages/analytics/modules/analytics

1 file changed

+32
-4
lines changed

packages/analytics/modules/analytics/client.ts

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,37 @@ import { browser } from '@wxt-dev/browser';
1313

1414
const ANALYTICS_PORT = '@wxt-dev/analytics';
1515

16+
// Based on https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/manifest.json/background#browser_support
17+
function isBackgroundScript(): boolean {
18+
if (!browser?.runtime?.getManifest || !location.protocol.endsWith('extension:')) {
19+
return false;
20+
}
21+
22+
const { background, background_page: backgroundPageWXT, manifest_version } = browser.runtime.getManifest();
23+
// Misonfiguration or Non-WXT Contenxt Check
24+
// Force check page attribute for possible configurations
25+
const backgroundPageManifest = (background as any)?.page;
26+
27+
const backgoundPageorScriptsCheck =
28+
location.pathname === '/_generated_background_page.html' ||
29+
(backgroundPageManifest && location.pathname.endsWith(backgroundPageManifest)) ||
30+
(backgroundPageWXT && location.pathname.endsWith(backgroundPageWXT));
31+
32+
if (manifest_version === 3) {
33+
try {
34+
return self instanceof ServiceWorkerGlobalScope &&
35+
// Check if called inside manifest defined service worker file
36+
background?.service_worker !== undefined && location.pathname.endsWith(background.service_worker);
37+
// oxlint-disable-next-line no-unused-vars
38+
} catch (e) {
39+
// Return false for non-service worker contexts
40+
return backgoundPageorScriptsCheck;
41+
}
42+
}
43+
44+
return backgoundPageorScriptsCheck;
45+
}
46+
1647
export function createAnalytics(config?: AnalyticsConfig): Analytics {
1748
if (!browser?.runtime?.id)
1849
throw Error(
@@ -24,10 +55,7 @@ export function createAnalytics(config?: AnalyticsConfig): Analytics {
2455
);
2556
}
2657

27-
// TODO: This only works for standard WXT extensions, add a more generic
28-
// background script detector that works with non-WXT projects.
29-
if (location.pathname === '/background.js')
30-
return createBackgroundAnalytics(config);
58+
if (isBackgroundScript()) return createBackgroundAnalytics(config);
3159

3260
return createFrontendAnalytics();
3361
}

0 commit comments

Comments
 (0)