Skip to main content
The background script (service worker in Manifest V3) handles API communication on behalf of content scripts. It receives messages from content scripts and forwards them to the Composite API.

Basic Setup

// background.js
import { HttpTransport, createBackgroundHandler } from '@composite-inc/composite-js';

// Create transport for API communication
const transport = new HttpTransport({
  apiKey: 'pk_your_api_key',
  apiHost: 'https://prod.alb.us.api.composite.com',
});

// Setup message handler for content scripts
createBackgroundHandler(transport);

console.log('[Composite] Background script initialized');
The background script doesn’t call composite.init(). It only handles message passing from content scripts to the API using createBackgroundHandler().

How It Works

  1. Content scripts capture events and session recordings
  2. They send messages to the background script via Chrome’s message passing
  3. The background script receives these messages and forwards them to the API
  4. This architecture is required because content scripts cannot make direct network requests to external APIs

Advanced Configuration

You can configure the transport with additional options:
// background.js
import { HttpTransport, createBackgroundHandler } from '@composite-inc/composite-js';

const transport = new HttpTransport({
  apiKey: 'pk_your_api_key',
  apiHost: 'https://prod.alb.us.api.composite.com',

  // Optional configuration
  flushInterval: 2000,     // Batch events every 2 seconds
  maxBatchSize: 50,        // Max events per batch
  retryLimit: 3,           // Retry failed requests
  timeout: 10000           // Request timeout in ms
});

createBackgroundHandler(transport);

With Lifecycle Events

// background.js
import { HttpTransport, createBackgroundHandler } from '@composite-inc/composite-js';

const transport = new HttpTransport({
  apiKey: 'pk_your_api_key',
  apiHost: 'https://prod.alb.us.api.composite.com',
});

createBackgroundHandler(transport);

// Extension lifecycle events
chrome.runtime.onInstalled.addListener((details) => {
  if (details.reason === 'install') {
    console.log('[Composite] Extension installed');
  } else if (details.reason === 'update') {
    console.log('[Composite] Extension updated');
  }
});

chrome.runtime.onStartup.addListener(() => {
  console.log('[Composite] Browser started');
});

What’s Next?