or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/npm-workbox-google-analytics

Queues failed Google Analytics requests and uses the Background Sync API to replay them when the network is available

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/workbox-google-analytics@7.3.x

To install, run

npx @tessl/cli install tessl/npm-workbox-google-analytics@7.3.0

index.mddocs/

Workbox Google Analytics

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.

Package Information

  • Package Name: workbox-google-analytics
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install workbox-google-analytics

Core Imports

import { initialize } from "workbox-google-analytics";

For CommonJS:

const { initialize } = require("workbox-google-analytics");

Basic Usage

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
  }
});

Architecture

Workbox Google Analytics is built around several key components:

  • Background Sync Integration: Uses the Background Sync API to queue failed requests and replay them when connectivity is restored
  • Request Queuing: Automatically captures failed Google Analytics requests (GET and POST) and stores them for later replay
  • Script Caching: Implements intelligent caching for Google Analytics scripts (analytics.js, gtag.js, gtm.js) using NetworkFirst strategy
  • Parameter Management: Handles queue time (qt) parameter calculation and supports custom parameter overrides for replayed requests
  • Multi-endpoint Support: Supports all Google Analytics collection endpoints including experimental paths like /r/collect

Capabilities

Initialize Analytics Offline Support

Sets 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:

  1. Script Caching: Automatically caches Google Analytics scripts using NetworkFirst strategy:

    • analytics.js from www.google-analytics.com
    • gtag.js from www.googletagmanager.com
    • gtm.js from www.googletagmanager.com
  2. Request Interception: Intercepts all Google Analytics requests to collection endpoints:

    • /collect (standard endpoint)
    • /r/collect (experimental endpoint)
    • /j/collect (experimental endpoint)
    • Any endpoint matching pattern /^\/(\w+\/)?collect/
  3. Failed Request Handling: When Analytics requests fail due to network issues:

    • Automatically queues the request with timestamp
    • Stores both GET and POST requests
    • Maintains original request parameters and body
  4. Background Sync Replay: When network connectivity is restored:

    • Automatically replays queued requests
    • Calculates and adds qt (queue time) parameter for accurate timing
    • Applies parameterOverrides if configured
    • Executes hitFilter function if provided
    • Converts all replayed requests to POST for reliability
  5. Queue Management:

    • Uses queue name: workbox-google-analytics
    • Default retention time: 2880 minutes (48 hours)
    • Automatically retries failed replays

Usage 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:

  • Failed replay attempts are automatically requeued for retry
  • Requests are discarded after the maximum retention time (2880 minutes/48 hours)
  • Network errors during replay don't affect the original user experience
  • All replay operations are performed in the background without blocking