@@ -13,6 +13,37 @@ import { browser } from '@wxt-dev/browser';
13
13
14
14
const ANALYTICS_PORT = '@wxt-dev/analytics' ;
15
15
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
+
16
47
export function createAnalytics ( config ?: AnalyticsConfig ) : Analytics {
17
48
if ( ! browser ?. runtime ?. id )
18
49
throw Error (
@@ -24,10 +55,7 @@ export function createAnalytics(config?: AnalyticsConfig): Analytics {
24
55
) ;
25
56
}
26
57
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 ) ;
31
59
32
60
return createFrontendAnalytics ( ) ;
33
61
}
0 commit comments