0
# Workbox Google Analytics
1
2
Workbox Google Analytics provides offline Google Analytics functionality for Progressive Web Apps by leveraging service worker capabilities to queue failed analytics requests and replay them when network connectivity is restored. It automatically handles Google Analytics Measurement Protocol requests, Google Tag Manager, and gtag.js analytics scripts with intelligent background sync capabilities.
3
4
## Package Information
5
6
- **Package Name**: workbox-google-analytics
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install workbox-google-analytics`
10
11
## Core Imports
12
13
```typescript
14
import { initialize } from "workbox-google-analytics";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { initialize } = require("workbox-google-analytics");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { initialize } from "workbox-google-analytics";
27
28
// Basic setup with default configuration
29
initialize();
30
31
// Setup with custom cache name and parameter overrides
32
initialize({
33
cacheName: 'my-analytics-cache',
34
parameterOverrides: {
35
cd1: 'offline-replay', // Custom dimension to mark replayed hits
36
},
37
hitFilter: (params) => {
38
// Modify parameters before replaying failed requests
39
params.set('cm1', '1'); // Custom metric for replay events
40
}
41
});
42
```
43
44
## Architecture
45
46
Workbox Google Analytics is built around several key components:
47
48
- **Background Sync Integration**: Uses the Background Sync API to queue failed requests and replay them when connectivity is restored
49
- **Request Queuing**: Automatically captures failed Google Analytics requests (GET and POST) and stores them for later replay
50
- **Script Caching**: Implements intelligent caching for Google Analytics scripts (analytics.js, gtag.js, gtm.js) using NetworkFirst strategy
51
- **Parameter Management**: Handles queue time (`qt`) parameter calculation and supports custom parameter overrides for replayed requests
52
- **Multi-endpoint Support**: Supports all Google Analytics collection endpoints including experimental paths like `/r/collect`
53
54
## Capabilities
55
56
### Initialize Analytics Offline Support
57
58
Sets up offline Google Analytics functionality with automatic request queuing and replay capabilities.
59
60
```typescript { .api }
61
/**
62
* Initializes offline Google Analytics support with Background Sync
63
* @param options - Optional configuration for cache name, parameter overrides, and hit filtering
64
*/
65
function initialize(options?: GoogleAnalyticsInitializeOptions): void;
66
67
interface GoogleAnalyticsInitializeOptions {
68
/** The cache name to store and retrieve analytics.js. Defaults to workbox-core cache names */
69
cacheName?: string;
70
/** Measurement Protocol parameters, expressed as key/value pairs, to be added to replayed requests */
71
parameterOverrides?: {[paramName: string]: string};
72
/** Function that allows you to modify the hit parameters prior to replaying the hit */
73
hitFilter?: (params: URLSearchParams) => void;
74
}
75
```
76
77
**Detailed Functionality:**
78
79
1. **Script Caching**: Automatically caches Google Analytics scripts using NetworkFirst strategy:
80
- `analytics.js` from `www.google-analytics.com`
81
- `gtag.js` from `www.googletagmanager.com`
82
- `gtm.js` from `www.googletagmanager.com`
83
84
2. **Request Interception**: Intercepts all Google Analytics requests to collection endpoints:
85
- `/collect` (standard endpoint)
86
- `/r/collect` (experimental endpoint)
87
- `/j/collect` (experimental endpoint)
88
- Any endpoint matching pattern `/^\/(\w+\/)?collect/`
89
90
3. **Failed Request Handling**: When Analytics requests fail due to network issues:
91
- Automatically queues the request with timestamp
92
- Stores both GET and POST requests
93
- Maintains original request parameters and body
94
95
4. **Background Sync Replay**: When network connectivity is restored:
96
- Automatically replays queued requests
97
- Calculates and adds `qt` (queue time) parameter for accurate timing
98
- Applies `parameterOverrides` if configured
99
- Executes `hitFilter` function if provided
100
- Converts all replayed requests to POST for reliability
101
102
5. **Queue Management**:
103
- Uses queue name: `workbox-google-analytics`
104
- Default retention time: 2880 minutes (48 hours)
105
- Automatically retries failed replays
106
107
**Usage Examples:**
108
109
```typescript
110
// Basic initialization - uses default cache and no customization
111
initialize();
112
113
// Custom cache name for analytics scripts
114
initialize({
115
cacheName: 'my-custom-analytics-cache'
116
});
117
118
// Add custom parameters to identify replayed requests
119
initialize({
120
parameterOverrides: {
121
cd1: 'offline-replay', // Custom dimension 1
122
cm1: '1' // Custom metric 1
123
}
124
});
125
126
// Filter and modify requests before replay
127
initialize({
128
hitFilter: (params) => {
129
// Add custom tracking for replayed events
130
if (params.get('t') === 'event') {
131
params.set('ea', params.get('ea') + '_replayed');
132
}
133
134
// Remove sensitive parameters if needed
135
params.delete('uip'); // Remove IP override
136
}
137
});
138
139
// Full configuration example
140
initialize({
141
cacheName: 'offline-analytics',
142
parameterOverrides: {
143
cd1: 'service-worker',
144
cd2: 'offline-replay'
145
},
146
hitFilter: (params) => {
147
// Mark all replayed hits with special category
148
if (params.get('t') === 'pageview') {
149
params.set('dp', params.get('dp') + '?replayed=true');
150
}
151
}
152
});
153
```
154
155
**Error Handling:**
156
157
- Failed replay attempts are automatically requeued for retry
158
- Requests are discarded after the maximum retention time (2880 minutes/48 hours)
159
- Network errors during replay don't affect the original user experience
160
- All replay operations are performed in the background without blocking