OneSignal Web Push SDK

repository·main·Indexed 19 days ago

https://github.com/onesignal/onesignal-website-sdk

SDK for integrating web push notifications into websites across Chrome, Safari, and Firefox. Includes documentation on local development using a Vite-based sandbox, build configurations for different API environments, and a migration guide for v16 which introduces a user-centered model featuring the OneSignal.User, OneSignal.Notifications, and OneSignal.Slidedown namespaces.

Tokens
10.7K
Snippets
36
Records
49
Agent score
60%

What's inside onesignal-website-sdk

  1. Handle Fake Timers and IndexedDB safely

    main

    Using vi.useFakeTimers() without restrictions can break fake-indexeddb by interfering with its internal async operations, causing tests to hang.

    Follow these rules:

    1. Avoid unrestricted fake timers: Never call vi.useFakeTimers() without a toFake list if your code interacts with IndexedDB.
    2. Use specific timer APIs: If you only need to fake certain functions, pass a toFake array.
    3. Use mockDelay for time-based delays: Instead of fake timers, use the mockDelay helper to make delay functions resolve immediately. This is safer and allows you to assert on the requested delay duration using a spy.
    // Only fake specific APIs to avoid breaking IndexedDB
    vi.useFakeTimers({ toFake: ['setInterval'] });
    vi.useFakeTimers({ toFake: ['Date'] });
    vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
    
    // Using mockDelay to avoid time-based waits
    import { mockDelay } from '__test__/support/helpers/setup';
    import { delay as delaySpy } from 'src/shared/helpers/general';
    
    // Call at the top level of the test file
    mockDelay();
    
    // Assert that the correct delay was requested
    expect(delaySpy).toHaveBeenCalledWith(30000);
  2. Migrate to the User Model SDK (v16)

    main

    In version 16, OneSignal shifted from a device-centered model to a user-centered model. This change introduces three core concepts to replace the previous 'player' concept:

    • Users: The primary entity that owns subscriptions. Users are identified via Aliases.
    • Subscriptions: The communication methods a user uses to receive messages (e.g., push notifications, SMS, email).
    • Aliases: Identifiers that point to a user, consisting of a label and an id. A single user can have multiple aliases (e.g., an external_id from your app and an ID from another integrated service).

    When using OneSignal.login(id), the SDK uses external_id as the default alias label.

  3. Set up local development for the SDK

    main

    To develop on the SDK locally, use the vp command-line tool to manage dependencies and run the development server.

    1. Install dependencies: vp install
    2. Start the dev server: vp run dev

    The development server will run on port 4001. Note that the code utilizes navigator.register on OneSignalSDKWorker.js to register the service worker.

    vp install
    vp run dev
  4. Preview the SDK bundle in a sandbox

    main

    To test the actual built SDK bundle in a sandbox environment, use the preview directory. This process builds the SDK from the repository root and then launches a Vite-based sandbox server on https://localhost:4001.

    Available commands:

    • cd preview && vp run start: Starts the sandbox targeting the production OneSignal API.
    • cd preview && vp run start:dev-stag: Starts the sandbox targeting the staging OneSignal API.

    For full configuration details, refer to preview/README.md.

    cd preview && vp run start
  5. Build the OneSignal Web SDK

    main

    You can build the SDK from the repository root using the vp run build command. You can specify the build environment and the API environment independently using the pattern build:<build-env>-<api-env>.

    Build Environments

    • <build-env>: dev, staging, or prod.
    • <api-env>: dev, staging, or prod.

    Examples

    • vp run build:dev: Standard development build.
    • vp run build:dev-prod: Builds with BUILD_TYPE=development but points the SDK to the production API.
    • vp run build:dev-dev: Builds for development and points to a local/development API.
    # From the repo root
    # Build for development environment using production API
    vp run build:dev-prod
  6. Run the WebSDK Sandbox Environment

    main

    The WebSDK Sandbox is a Vite-based environment used to test built OneSignal Web SDK versions against a real browser. It serves the SDK files, manifest, and service worker, and maps SDK builds from the repository's build directory to a local URL.

    Steps to Run

    1. Navigate to the preview/ directory.
    2. Execute a run script based on your testing needs:
      • vp run start: Standard start.
      • vp run start:dev: Tests the local SDK against the production OneSignal API.
      • vp run start:dev-stag: Tests the local SDK against the staging OneSignal API.
    3. Open your browser to https://localhost:4001?app_id=<your-app-id> (replace <your-app-id> with your actual OneSignal App ID).

    Note on HTTPS and Certificates

    By default, the sandbox uses HTTPS on port 4001. On the first run, vite-plugin-mkcert will attempt to install a local root CA. If you prefer to manage this manually, you can install mkcert via brew install mkcert and run mkcert -install.

    Warning: Push subscription flows require HTTPS because the service worker import path is hard-coded to an HTTPS URL.

    cd preview
    # Test local SDK against production API
    vp run start:dev
    
    # Test local SDK against staging API
    vp run start:dev-stag
  7. Create a basic test file template

    main

    When writing tests for the SDK, use the following template to ensure the environment is correctly initialized and mocks are reset between tests. This template uses TestEnvironment.initialize() in beforeEach and vi.resetAllMocks() in afterEach to maintain test isolation.

    import { TestEnvironment } from '../../support/environment/TestEnvironment';
    
    // mock an entire file
    vi.mock('../../../src/MyFile');
    
    describe('My tests', () => {
      beforeEach(() => {
        TestEnvironment.initialize();
      });
    
      afterEach(() => {
        vi.resetAllMocks();
      });
    
      test('This is a test description', () => {});
    });
  8. Get started with the OneSignal Web Push SDK

    main

    The OneSignal Web Push SDK enables your website visitors to receive push notifications. You can send custom notification content, target specific users, and trigger automated messages.

    To begin integration, follow the official Web Push Quickstart guide.

    Important: Always reference the OneSignal SDK via the official CDN URL provided in the setup documentation rather than hosting a local copy. This ensures your site always uses the latest version containing the newest features and bug fixes.

  9. Update SDK script imports for v16

    main

    To use version 16, you must update the script source on your web pages and within your Service Worker file.

    Web Pages

    Replace the old OneSignalSDK.js script with the new OneSignalSDK.page.js using the defer attribute.

    Service Worker

    In your OneSignalSDKWorker.js, update the importScripts call to point to OneSignalSDK.sw.js.

    <!-- On your web pages -->
    <script src="https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.page.js" defer></script>
    
    <!-- In OneSignalSDKWorker.js -->
    importScripts('https://cdn.onesignal.com/sdks/web/v16/OneSignalSDK.sw.js');
  10. How to control notification display with IDisplayableOSNotification

    main

    The IDisplayableOSNotification interface extends IOSNotification and provides a method to manually trigger the system notification display. This is primarily used when intercepting the foregroundWillDisplay event.

    Workflow:

    1. Listen for the foregroundWillDisplay event.
    2. Call event.preventDefault() to suppress the automatic system notification.
    3. Call event.notification.display() to manually show the notification at a later time or under specific conditions.

    Note: Do not call preventDefault() after calling display(), as it will have no effect.

  11. Configure Custom Origins for Build and API

    main

    You can override the default origins for the SDK files (Build Origin) and the OneSignal API (API Origin) using environment variables during the build process.

    Environment Variables

    • BUILD_ORIGIN: The host from which the SDK files are fetched. Defaults to localhost.
    • API_ORIGIN: The host for OneSignal API calls. Defaults to onesignal.com.

    Usage Examples

    • Custom API Origin: To point a development build to a specific API host (e.g., texas): API_ORIGIN=texas vp run build:dev-prod
    • Custom Build and API Origins: To point the SDK files to localhost and the API to a custom host texas: BUILD_ORIGIN=localhost API_ORIGIN=texas vp run build:dev-dev

    Important: Ensure your custom origins are compatible with your chosen environment. For example, a prod API environment will ignore custom API_ORIGIN parameters.

    # Example: Set build origin to 'texas' and API to production
    API_ORIGIN=texas vp run build:dev-prod
    
    # Example: Set build origin to 'localhost' and API to 'texas'
    BUILD_ORIGIN=localhost API_ORIGIN=texas vp run build:dev-dev
  12. Migrate custom Service Worker configuration

    main

    If you previously configured the Service Worker using global constants on the OneSignal object, you must now move these settings into the OneSignal.init() configuration object using camelCase keys.

    // Old way (v15 and below)
    OneSignal.SERVICE_WORKER_PARAM = { scope: '/myCustomScope' };
    OneSignal.SERVICE_WORKER_PATH = '/myPath/OneSignalSDKWorker.js';
    
    // New way (v16)
    await OneSignal.init({
      // ... other params like appId
      serviceWorkerParam: { scope: '/myCustomScope' },
      serviceWorkerPath: '/myPath/OneSignalSDKWorker.js',
    });