Queues failed Google Analytics requests and uses the Background Sync API to replay them when the network is available
npx @tessl/cli install tessl/npm-workbox-google-analytics@7.3.0Workbox 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.
npm install workbox-google-analyticsimport { initialize } from "workbox-google-analytics";For CommonJS:
const { initialize } = require("workbox-google-analytics");import { initialize } from "workbox-google-analytics";
// Basic setup with default configuration
initialize();
// Setup with custom cache name and parameter overrides
initialize({
cacheName: 'my-analytics-cache',
parameterOverrides: {
cd1: 'offline-replay', // Custom dimension to mark replayed hits
},
hitFilter: (params) => {
// Modify parameters before replaying failed requests
params.set('cm1', '1'); // Custom metric for replay events
}
});Workbox Google Analytics is built around several key components:
qt) parameter calculation and supports custom parameter overrides for replayed requests/r/collectSets up offline Google Analytics functionality with automatic request queuing and replay capabilities.
/**
* Initializes offline Google Analytics support with Background Sync
* @param options - Optional configuration for cache name, parameter overrides, and hit filtering
*/
function initialize(options?: GoogleAnalyticsInitializeOptions): void;
interface GoogleAnalyticsInitializeOptions {
/** The cache name to store and retrieve analytics.js. Defaults to workbox-core cache names */
cacheName?: string;
/** Measurement Protocol parameters, expressed as key/value pairs, to be added to replayed requests */
parameterOverrides?: {[paramName: string]: string};
/** Function that allows you to modify the hit parameters prior to replaying the hit */
hitFilter?: (params: URLSearchParams) => void;
}Detailed Functionality:
Script Caching: Automatically caches Google Analytics scripts using NetworkFirst strategy:
analytics.js from www.google-analytics.comgtag.js from www.googletagmanager.comgtm.js from www.googletagmanager.comRequest Interception: Intercepts all Google Analytics requests to collection endpoints:
/collect (standard endpoint)/r/collect (experimental endpoint)/j/collect (experimental endpoint)/^\/(\w+\/)?collect/Failed Request Handling: When Analytics requests fail due to network issues:
Background Sync Replay: When network connectivity is restored:
qt (queue time) parameter for accurate timingparameterOverrides if configuredhitFilter function if providedQueue Management:
workbox-google-analyticsUsage Examples:
// Basic initialization - uses default cache and no customization
initialize();
// Custom cache name for analytics scripts
initialize({
cacheName: 'my-custom-analytics-cache'
});
// Add custom parameters to identify replayed requests
initialize({
parameterOverrides: {
cd1: 'offline-replay', // Custom dimension 1
cm1: '1' // Custom metric 1
}
});
// Filter and modify requests before replay
initialize({
hitFilter: (params) => {
// Add custom tracking for replayed events
if (params.get('t') === 'event') {
params.set('ea', params.get('ea') + '_replayed');
}
// Remove sensitive parameters if needed
params.delete('uip'); // Remove IP override
}
});
// Full configuration example
initialize({
cacheName: 'offline-analytics',
parameterOverrides: {
cd1: 'service-worker',
cd2: 'offline-replay'
},
hitFilter: (params) => {
// Mark all replayed hits with special category
if (params.get('t') === 'pageview') {
params.set('dp', params.get('dp') + '?replayed=true');
}
}
});Error Handling: