Skip to content

Commit 0f0daf3

Browse files
authored
feat: New @wxt-dev/analytics package (#790)
Co-authored-by: aklinker1 <[email protected]>
1 parent 51b315f commit 0f0daf3

File tree

22 files changed

+1114
-8
lines changed

22 files changed

+1114
-8
lines changed

.github/workflows/release.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ on:
77
default: wxt
88
type: choice
99
options:
10+
- analytics
1011
- auto-icons
1112
- i18n
1213
- module-react

.github/workflows/sync-releases.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ on:
77
default: wxt
88
type: choice
99
options:
10+
- analytics
1011
- auto-icons
1112
- i18n
1213
- module-react

docs/.vitepress/config.ts

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { version as i18nVersion } from '../../packages/i18n/package.json';
1414
import { version as autoIconsVersion } from '../../packages/auto-icons/package.json';
1515
import { version as unocssVersion } from '../../packages/unocss/package.json';
1616
import { version as storageVersion } from '../../packages/storage/package.json';
17+
import { version as analyticsVersion } from '../../packages/analytics/package.json';
1718
import knowledge from 'vitepress-knowledge';
1819

1920
const title = 'Next-gen Web Extension Framework';
@@ -24,6 +25,14 @@ const ogTitle = `${title}${titleSuffix}`;
2425
const ogUrl = 'https://wxt.dev';
2526
const ogImage = 'https://wxt.dev/social-preview.png';
2627

28+
const otherPackages = {
29+
analytics: analyticsVersion,
30+
'auto-icons': autoIconsVersion,
31+
i18n: i18nVersion,
32+
storage: storageVersion,
33+
unocss: unocssVersion,
34+
};
35+
2736
// https://vitepress.dev/reference/site-config
2837
export default defineConfig({
2938
extends: knowledge({
@@ -109,12 +118,12 @@ export default defineConfig({
109118
'https://github.com/wxt-dev/wxt/blob/main/packages/wxt/CHANGELOG.md',
110119
),
111120
]),
112-
navItem('Other Packages', [
113-
navItem(`@wxt-dev/storage — ${storageVersion}`, '/storage'),
114-
navItem(`@wxt-dev/auto-icons — ${autoIconsVersion}`, '/auto-icons'),
115-
navItem(`@wxt-dev/i18n${i18nVersion}`, '/i18n'),
116-
navItem(`@wxt-dev/unocss — ${unocssVersion}`, '/unocss'),
117-
]),
121+
navItem(
122+
'Other Packages',
123+
Object.entries(otherPackages).map(([name, version]) =>
124+
navItem(`@wxt-dev/${name}${version}`, `/${name}`),
125+
),
126+
),
118127
]),
119128
],
120129

docs/analytics.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<!--@include: ../packages/analytics/README.md-->

docs/assets/init-demo.gif

-1013 Bytes
Loading

packages/analytics/README.md

Lines changed: 269 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,269 @@
1+
# WXT Analytics
2+
3+
Report analytics events from your web extension extension.
4+
5+
## Supported Analytics Providers
6+
7+
- [Google Analytics 4 (Measurement Protocol)](#google-analytics-4-measurement-protocol)
8+
- [Umami](#umami)
9+
10+
## Install With WXT
11+
12+
1. Install the NPM package:
13+
```bash
14+
pnpm i @wxt-dev/analytics
15+
```
16+
2. In your `wxt.config.ts`, add the WXT module:
17+
```ts
18+
export default defineConfig({
19+
modules: ['@wxt-dev/analytics/module'],
20+
});
21+
```
22+
3. In your `<srcDir>/app.config.ts`, add a provider:
23+
24+
```ts
25+
// <srcDir>/app.config.ts
26+
import { umami } from '@wxt-dev/analytics/providers/umami';
27+
28+
export default defineAppConfig({
29+
analytics: {
30+
debug: true,
31+
providers: [
32+
// ...
33+
],
34+
},
35+
});
36+
```
37+
38+
4. Then use the `#analytics` module to report events:
39+
40+
```ts
41+
import { analytics } from '#analytics';
42+
43+
await analytics.track('some-event');
44+
await analytics.page();
45+
await analytics.identify('some-user-id');
46+
analytics.autoTrack(document.body);
47+
```
48+
49+
## Install Without WXT
50+
51+
1. Install the NPM package:
52+
```bash
53+
pnpm i @wxt-dev/analytics
54+
```
55+
2. Create an `analytics` instance:
56+
57+
```ts
58+
// utils/analytics.ts
59+
import { createAnalytics } from '@wxt-dev/analytics';
60+
61+
export const analytics = createAnalytics({
62+
providers: [
63+
// ...
64+
],
65+
});
66+
```
67+
68+
3. Import your analytics module in the background to initialize the message listener:
69+
```ts
70+
// background.ts
71+
import './utils/analytics';
72+
```
73+
4. Then use your `analytics` instance to report events:
74+
75+
```ts
76+
import { analytics } from './utils/analytics';
77+
78+
await analytics.track('some-event');
79+
await analytics.page();
80+
await analytics.identify('some-user-id');
81+
analytics.autoTrack(document.body);
82+
```
83+
84+
## Providers
85+
86+
### Google Analytics 4 (Measurement Protocol)
87+
88+
The [Measurement Protocol](https://developers.google.com/analytics/devguides/collection/protocol/ga4) is an alternative to GTag for reporting events to Google Analytics for MV3 extensions.
89+
90+
> [Why use the Measurement Protocol instead of GTag?](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#measurement-protocol)
91+
92+
Follow [Google's documentation](https://developer.chrome.com/docs/extensions/how-to/integrate/google-analytics-4#setup-credentials) to obtain your credentials and put them in your `.env` file:
93+
94+
```dotenv
95+
WXT_GA_API_SECRET='...'
96+
```
97+
98+
Then add the `googleAnalytics4` provider to your `<srcDir>/app.config.ts` file:
99+
100+
```ts
101+
import { googleAnalytics4 } from '@wxt-dev/analytics/providers/google-analytics-4';
102+
103+
export default defineAppConfig({
104+
analytics: {
105+
providers: [
106+
googleAnalytics4({
107+
apiSecret: import.meta.env.WXT_GA_API_SECRET,
108+
measurementId: '...',
109+
}),
110+
],
111+
},
112+
});
113+
```
114+
115+
### Umami
116+
117+
[Umami](https://umami.is/) is a privacy-first, open source analytics platform.
118+
119+
In Umami's dashboard, create a new website. The website's name and domain can be anything. Obviously, an extension doesn't have a domain, so make one up if you don't have one.
120+
121+
After the website has been created, save the website ID and domain to your `.env` file:
122+
123+
```dotenv
124+
WXT_UMAMI_WEBSITE_ID='...'
125+
WXT_UMAMI_DOMAIN='...'
126+
```
127+
128+
Then add the `umami` provider to your `<srcDir>/app.config.ts` file:
129+
130+
```ts
131+
import { umami } from '@wxt-dev/analytics/providers/umami';
132+
133+
export default defineAppConfig({
134+
analytics: {
135+
providers: [
136+
umami({
137+
apiUrl: 'https://<your-umami-instance>/api',
138+
websiteId: import.meta.env.WXT_UMAMI_WEBSITE_ID,
139+
domain: import.meta.env.WXT_UMAMI_DOMAIN,
140+
}),
141+
],
142+
},
143+
});
144+
```
145+
146+
### Custom Provider
147+
148+
If your analytics platform is not supported, you can provide an implementation of the `AnalyticsProvider` type in your `app.config.ts` instead:
149+
150+
```ts
151+
import { defineAnalyticsProvider } from '@wxt-dev/analytics/client';
152+
153+
interface CustomAnalyticsOptions {
154+
// ...
155+
}
156+
157+
const customAnalytics = defineAnalyticsProvider<CustomAnalyticsOptions>(
158+
(analytics, analyticsConfig, providerOptions) => {
159+
// ...
160+
},
161+
);
162+
163+
export default defineAppConfig({
164+
analytics: {
165+
providers: [
166+
customAnalytics({
167+
// ...
168+
}),
169+
],
170+
},
171+
});
172+
```
173+
174+
Example `AnalyticsProvider` implementations can be found at [`./modules/analytics/providers`](https://github.com/wxt-dev/wxt/tree/main/packages/analytics/modules/analytics/providers).
175+
176+
## User Properties
177+
178+
User ID and properties are stored in `browser.storage.local`. To change this or customize where these values are stored, use the `userId` and `userProperties` config:
179+
180+
```ts
181+
// app.config.ts
182+
import { storage } from 'wxt/storage';
183+
184+
export default defineAppConfig({
185+
analytics: {
186+
userId: storage.defineItem('local:custom-user-id-key'),
187+
userProperties: storage.defineItem('local:custom-user-properties-key'),
188+
},
189+
});
190+
```
191+
192+
To set the values at runtime, use the `identify` function:
193+
194+
```ts
195+
await analytics.identify(userId, userProperties);
196+
```
197+
198+
Alternatively, a common pattern is to use a random string as the user ID. This keeps the actual user information private, while still providing useful metrics in your analytics platform. This can be done very easily using WXT's storage API:
199+
200+
```ts
201+
// app.config.ts
202+
import { storage } from 'wxt/storage';
203+
204+
export default defineAppConfig({
205+
analytics: {
206+
userId: storage.defineItem('local:custom-user-id-key', {
207+
init: () => crypto.randomUUID(),
208+
}),
209+
},
210+
});
211+
```
212+
213+
If you aren't using `wxt` or `@wxt-dev/storage`, you can define custom implementations for the `userId` and `userProperties` config:
214+
215+
```ts
216+
const analytics = createAnalytics({
217+
userId: {
218+
getValue: () => ...,
219+
setValue: (userId) => ...,
220+
}
221+
})
222+
```
223+
224+
## Auto-track UI events
225+
226+
Call `analytics.autoTrack(container)` to automatically track UI events so you don't have to manually add them. Currently it:
227+
228+
- Tracks clicks to elements inside the `container`
229+
230+
In your extension's HTML pages, you'll want to call it with `document`:
231+
232+
```ts
233+
analytics.autoTrack(document);
234+
```
235+
236+
But in content scripts, you usually only care about interactions with your own UI:
237+
238+
```ts
239+
const ui = createIntegratedUi({
240+
// ...
241+
onMount(container) {
242+
analytics.autoTrack(container);
243+
},
244+
});
245+
ui.mount();
246+
```
247+
248+
## Enabling/Disabling
249+
250+
By default, **analytics is disabled**. You can configure how the value is stored (and change the default value) via the `enabled` config:
251+
252+
```ts
253+
// app.config.ts
254+
import { storage } from 'wxt/storage';
255+
256+
export default defineAppConfig({
257+
analytics: {
258+
enabled: storage.defineItem('local:analytics-enabled', {
259+
fallback: true,
260+
}),
261+
},
262+
});
263+
```
264+
265+
At runtime, you can call `setEnabled` to change the value:
266+
267+
```ts
268+
analytics.setEnabled(true);
269+
```

packages/analytics/app.config.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { defineAppConfig } from 'wxt/sandbox';
2+
import { googleAnalytics4 } from './modules/analytics/providers/google-analytics-4';
3+
import { umami } from './modules/analytics/providers/umami';
4+
5+
export default defineAppConfig({
6+
analytics: {
7+
debug: true,
8+
providers: [
9+
googleAnalytics4({
10+
apiSecret: '...',
11+
measurementId: '...',
12+
}),
13+
umami({
14+
apiUrl: 'https://umami.aklinker1.io/api',
15+
domain: 'analytics.wxt.dev',
16+
websiteId: '8f1c2aa4-fad3-406e-a5b2-33e8d4501716',
17+
}),
18+
],
19+
},
20+
});

packages/analytics/build.config.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import { defineBuildConfig } from 'unbuild';
2+
import { resolve } from 'node:path';
3+
4+
// Build module and plugins
5+
export default defineBuildConfig({
6+
rootDir: resolve(__dirname, 'modules/analytics'),
7+
outDir: resolve(__dirname, 'dist'),
8+
entries: [
9+
{ input: 'index.ts', name: 'module' },
10+
{ input: 'client.ts', name: 'index' },
11+
'background-plugin.ts',
12+
'types.ts',
13+
'providers/google-analytics-4.ts',
14+
'providers/umami.ts',
15+
],
16+
externals: ['#analytics'],
17+
replace: {
18+
'import.meta.env.NPM': 'true',
19+
},
20+
declaration: true,
21+
});
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>Popup</title>
7+
</head>
8+
<body>
9+
<label>
10+
<input id="enabledCheckbox" type="checkbox" />
11+
&emsp;Analytics enabled
12+
</label>
13+
<button id="button1">Button 1</button>
14+
<button class="cool-button">Button 2</button>
15+
<script type="module" src="./main.ts"></script>
16+
</body>
17+
</html>

0 commit comments

Comments
 (0)