# Web SDK


The OpenPush Web SDK puts web push on your site. One script tag (or one npm package) subscribes the browser, keeps the subscription healthy, carries the person's identity, tags and aliases, shows your prompts, and reports delivery receipts. A one-line service worker file on your site shows the notifications. OpenPush sends to browsers directly with standard Web Push. There is no Firebase project to create and no key to copy: OpenPush makes a key pair for each app and never shows the private half.

Like the mobile SDKs, it is receive-only. It has no send API: sending stays in the console, the REST API and the MCP server. The method names match the [iOS](sdk-ios.md), [Android](sdk-android.md) and [Unity](sdk-unity.md) SDKs, so one team can read all four.

## When to use

Add this SDK to any HTTPS site that should receive push from OpenPush. It works with a plain HTML site, a site built with a framework, and a site managed through a tag manager. Browsers on your site and phones in your apps share one audience, one segment language, one composer and one set of reports.

## Requirements

| Requirement | Value |
|---|---|
| SDK version | `1.1.0` |
| Browsers | Chrome, Edge and Firefox on computers and Android; Safari 16.4 or later on macOS; Safari on iPhone and iPad 16.4 or later, only as a Home Screen web app (see [iOS and iPadOS](#ios-and-ipados-home-screen-web-apps)) |
| Site | Served over HTTPS. One site address (origin) per OpenPush app |
| A file on your site | `openpush-sw.js`, one line long (see [Step 3](#step-3--the-worker-file)) |
| Credentials | Your app id. The SDK reads the app's public SDK key from the app's web config, so you never paste a key into your page |
| Server | Nothing to choose: the SDK talks to `https://app.openpush.ai` |
| Console | Website set up under **Settings › Push & In-App › Web** (see [Step 1](#step-1--set-up-the-site-in-the-console)) |

The SDK key is public by design. It can register a browser and post receipts and events, nothing more. The REST API key must never appear in a page. See [security-and-limits.md](security-and-limits.md).

## Packages

| Package | What it is |
|---|---|
| `https://app.openpush.ai/sdk/web/v2/openpush.js` | The script tag build. Defines `window.OpenPush` |
| `https://app.openpush.ai/sdk/web/v2/openpush-sw.js` | The worker code your one-line worker file imports |
| `@openpush/web` | The npm package: ESM and CommonJS builds with types. `import OpenPush from "@openpush/web"` |
| `@openpush/web/sw` | The worker file, for bundlers that copy it into `public/` |
| `@openpush/react` | `<OpenPushProvider>` and `useOpenPush()` for React and Next.js |
| `@openpush/vue` | A Vue 3 plugin and `useOpenPush()` |
| `@openpush/angular` | `provideOpenPush()`, `OpenPushModule.forRoot()` and `OpenPushService` |

The `v2` path always serves the newest release, so fixes reach your site without a code change. Every release is also served at its exact-version path, such as `https://app.openpush.ai/sdk/web/1.1.0/openpush.js`. That path keeps serving the same files after newer releases, so a page that pins a release keeps working; it does not get fixes, so use `v2` on a live site. The framework packages are thin: they start the SDK once and give you reactive state. They have the same version as `@openpush/web`.

## Install with AI

Working with a coding agent? Paste this prompt into it, in your site's project. It names the exact files and lines, what to leave alone, and how to check the result. The console's Install step shows the same prompt with your app id and site address filled in.

<!-- install-with-ai:web:start -->
<!-- Generated from partials/install-with-ai/web.md by scripts/sync-install-with-ai.mjs. Edit the partial, not this block. -->

```text
Install OpenPush web push on this website, for the OpenPush app "your-app-id". The site is https://www.example.com.

1. Add these two tags to the <head> of every page, in the shared layout or template:

<script src="https://app.openpush.ai/sdk/web/v2/openpush.js" defer></script>
<script>
  window.OpenPushDeferred = window.OpenPushDeferred || [];
  OpenPushDeferred.push(async function (OpenPush) {
    await OpenPush.initialize({ appId: "your-app-id" });
  });
</script>

2. Create a file named openpush-sw.js that contains exactly this one line:

importScripts("https://app.openpush.ai/sdk/web/v2/openpush-sw.js");

Put it where the site serves it at https://www.example.com/openpush-sw.js: the web root, or the public/ folder of a Next.js, React, Vue, Angular or Vite project.

3. Do not change anything else:
- Do not add code that asks for notification permission or shows a prompt. The prompts are set in the OpenPush console.
- Do not register another service worker at the site root, and do not unregister existing service workers.
- If the site already has a service worker at /, stop and tell me instead of replacing it.
- Do not host openpush-sw.js on a CDN or another domain. It must come from https://www.example.com.

4. Check that it works:
- Open https://www.example.com/openpush-sw.js. It must show the importScripts line, as JavaScript, with no redirect.
- Open the site in Chrome with the developer console open. Lines from the SDK start with [OpenPush]. There must be no [OpenPush] error.
- Then open the Verify step in the OpenPush console and press Check again.
```

<!-- install-with-ai:web:end -->

On a **Custom code** site, the prompts and the welcome notification come from your code, so the prompt is different. The console's Install step shows this one for a Custom code site:

<!-- install-with-ai:web-custom:start -->
<!-- Generated from partials/install-with-ai/web-custom.md by scripts/sync-install-with-ai.mjs. Edit the partial, not this block. -->

```text
Install OpenPush web push on this website with code, for the OpenPush app "your-app-id". The site is https://www.example.com. It uses Custom code: the prompts and the welcome notification come from the code below, not from the OpenPush console.

1. Install the package:

npm install @openpush/web

2. Start the SDK once per page load, in the browser only, in the site's entry point or root layout (in Next.js, inside a client component):

import OpenPush from "@openpush/web";

await OpenPush.initialize({
  appId: "your-app-id",
  prompts: [
    { id: "news", type: "slide_in", enabled: true, timing: { auto: true, page_views: 2, seconds: 10 } },
  ],
  welcomeNotification: { enabled: true, message: "Thanks for subscribing" },
});

Keep the prompts and welcomeNotification options in this call. If the project uses React, Vue 3 or Angular, you may use @openpush/react, @openpush/vue or @openpush/angular instead and pass the same options to its provider.

3. Create a file named openpush-sw.js that contains exactly this one line:

importScripts("https://app.openpush.ai/sdk/web/v2/openpush-sw.js");

Put it where the site serves it at https://www.example.com/openpush-sw.js: the web root, or the public/ folder of a Next.js, React, Vue, Angular or Vite project. "npx @openpush/web worker public" writes it there.

4. Do not change anything else:
- Do not call initialize more than once per page load, and do not call it during server-side rendering.
- Do not ask for notification permission when the page loads. Use the prompts option, or call OpenPush.Prompts.showSlideIn({ force: true }) from a click.
- Do not register another service worker at the site root, and do not unregister existing service workers.
- If the site already has a service worker at /, stop and tell me instead of replacing it.
- Do not host openpush-sw.js on a CDN or another domain. It must come from https://www.example.com.
- Do not put an OpenPush REST API key in the site. The app id is all the SDK needs.

5. Check that it works:
- Open https://www.example.com/openpush-sw.js. It must show the importScripts line, as JavaScript, with no redirect.
- Open the site in Chrome with the developer console open. Lines from the SDK start with [OpenPush]. There must be no [OpenPush] error.
- Then open the Verify step in the OpenPush console and press Check again.
```

<!-- install-with-ai:web-custom:end -->

## Step 1 — set up the site in the console

Open your app's **Settings › Push & In-App › Web** and follow the three steps:

1. **Site.** Choose the setup type, then give the site's name, address and icon.
2. **Install.** Copy the script snippet and download the one-line worker file.
3. **Verify.** OpenPush checks that your home page loads the SDK and that your site serves the worker file. Then you can subscribe your own browser and send yourself a test push.

The two setup types decide where the settings come from:

| Setup type | Prompts, welcome notification, click behaviour, worker location | Use it when |
|---|---|---|
| **Typical site** | The console. The SDK fetches them when the page loads; matching code options are ignored with one warning | You want to change prompts and wording without a deploy |
| **Custom code** | Your `initialize()` options | You want to control prompts from code, for example per page or per test group |

Switching to Custom code keeps the prompts and welcome notification you saved in the console, but the SDK stops using them. Switching back restores them.

One site address belongs to one app. `https://www.example.com` and `https://example.com` are different sites: pick the one your visitors use. For local testing, make a separate app whose address is your `http://localhost` origin.

## Step 2 — install the SDK

### Script tag

Put this in the `<head>` of every page:

```html
<script src="https://app.openpush.ai/sdk/web/v2/openpush.js" defer></script>
<script>
  window.OpenPushDeferred = window.OpenPushDeferred || [];
  OpenPushDeferred.push(async function (OpenPush) {
    await OpenPush.initialize({ appId: "your-app-id" });
  });
</script>
```

`OpenPushDeferred` is a queue. Functions you push before the SDK loads run after it loads, in order. Once one of them has called `initialize`, later ones wait for it to finish, so a tag or login call pushed further down the page runs after the SDK is ready:

```html
<script>
  window.OpenPushDeferred = window.OpenPushDeferred || [];
  OpenPushDeferred.push(function (OpenPush) {
    OpenPush.login("user-7");
  });
</script>
```

### npm

```sh
npm install @openpush/web
```

```js
import OpenPush from "@openpush/web";

await OpenPush.initialize({ appId: "your-app-id" });
```

Call `initialize` once per page load, in the browser only. A second call resolves at once with a warning and changes nothing. The npm build loads the prompt UI from `app.openpush.ai` when a prompt is needed. To bundle it instead, add `import "@openpush/web/prompts";`.

### React and Next.js

```sh
npm install @openpush/web @openpush/react
```

```jsx
// app/layout.tsx (Next.js App Router) or your root component
import { OpenPushProvider } from "@openpush/react";

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        <OpenPushProvider options={{ appId: "your-app-id" }}>{children}</OpenPushProvider>
      </body>
    </html>
  );
}
```

```jsx
import { useOpenPush } from "@openpush/react";

function NotifyButton() {
  const { OpenPush, permission, optedIn } = useOpenPush();
  if (optedIn) return null;
  return <button onClick={() => OpenPush.Notifications.requestPermission()}>Get notified</button>;
}
```

`useOpenPush()` returns the `OpenPush` object and reactive `permission`, `optedIn`, `subscriptionId` and `externalId`. The provider starts the SDK once per page load, also under React StrictMode, so you need no workaround for StrictMode's double effects. The provider file is a client component and does nothing on the server.

### Vue 3

```sh
npm install @openpush/web @openpush/vue
```

```js
import { createApp } from "vue";
import { OpenPushPlugin } from "@openpush/vue";
import App from "./App.vue";

createApp(App).use(OpenPushPlugin, { appId: "your-app-id" }).mount("#app");
```

In a component, `useOpenPush()` returns the same object and reactive state as in React. Templates can also use `$openpush`. Vue 2 is not supported.

### Angular

```sh
npm install @openpush/web @openpush/angular
```

```ts
// main.ts (standalone app)
import { bootstrapApplication } from "@angular/platform-browser";
import { provideOpenPush } from "@openpush/angular";
import { AppComponent } from "./app/app.component";

bootstrapApplication(AppComponent, {
  providers: [provideOpenPush({ appId: "your-app-id" })],
});
```

An app with NgModules imports `OpenPushModule.forRoot({ appId: "your-app-id" })` instead. Inject `OpenPushService` for the SDK object and for signals that hold the permission and subscription state. The SDK starts once, so route changes never start it again.

### Google Tag Manager

1. Create one **Custom HTML** tag that fires on **All Pages**, with the script tag snippet above in it.
2. Tags that run later, for example on login, push a function to the same queue:

   ```html
   <script>
     window.OpenPushDeferred = window.OpenPushDeferred || [];
     OpenPushDeferred.push(function (OpenPush) {
       OpenPush.login({{User ID}});
     });
   </script>
   ```

3. A tag that must wait for the SDK can use a **Custom Event** trigger on `openpush.initialized`. The SDK pushes that event to `dataLayer` once per page, when `initialize` finishes.

A tag manager cannot host the worker file. `openpush-sw.js` must still be a file on your site (Step 3).

## Step 3 — the worker file

Your site hosts one file, `openpush-sw.js`, with one line in it:

```js
importScripts("https://app.openpush.ai/sdk/web/v2/openpush-sw.js");
```

The console's Install step has a **Download** button for it.

- **Where it goes:** at the root of your site, so it is served at `https://www.example.com/openpush-sw.js`. In a framework project, put it in the folder that is copied to the site root as is: `public/` for Next.js, Vite, React, Vue and Angular projects. With npm, `npx @openpush/web worker public` writes it there for you.
- **How it must be served:** from your own site address (not a CDN or another domain), as JavaScript, with status 200 and no redirect. Browsers refuse a worker that redirects.
- **Why it is so short:** the worker code lives on `app.openpush.ai`, so fixes reach your site without a deploy. Browsers check the worker for updates at least once a day.

**Worker file load.** When you send to a large audience, every subscribed browser may fetch `openpush-sw.js` from your site at about the same time. Serve it with normal caching and keep it to the one line. The SDK code itself comes from `app.openpush.ai`. [Throttling](sending-messages.md) a large send also spreads these fetches out.

If your site already has a service worker, read [Coexisting with a PWA worker](#coexisting-with-a-pwa-worker) before you add the file. To put the file somewhere else, see [Changing the worker location](#changing-the-worker-location).

## Step 4 — initialize

`OpenPush.initialize(options)` starts the SDK. `appId` is the only required option.

| Option | Type | Default | Typical site | Custom code |
|---|---|---|---|---|
| `appId` | string | required | code | code |
| `serviceWorkerPath` | string | `/openpush-sw.js` | console | code |
| `serviceWorkerScope` | string | `/` | console | code |
| `autoResubscribe` | boolean | `true` | console | code |
| `prompts` | array | none | console | code |
| `welcomeNotification` | `{enabled, title, message, url}` | on; title = the site name, message "Thanks for subscribing", a click opens the site | console | code |
| `clickBehavior` | `{match: "exact" \| "origin", action: "navigate" \| "focus"}` | `{match: "exact", action: "navigate"}` | console | code |
| `keepOnScreen` | boolean | `true` | console | code |
| `webhooks` | `{displayed?, clicked?, dismissed?, cors?}` | none; `cors: false` | console | code |
| `requiresConsent` | boolean | `false` | code | code |
| `allowLocalhost` | boolean | `false` | code | code |
| `defaultUrl` | string | the site address | code | code |
| `defaultTitle` | string | the site name | code | code |
| `logLevel` | `"none"`, `"error"`, `"warn"`, `"info"`, `"debug"`, `"trace"` | `"warn"` | code | code |
| `language` | string (BCP 47, for example `pt-BR`) | the browser's language | code | code |
| `promptsLanguage` | string | the effective `language` | code | code |
| `nonce` | string | none | code | code |
| `serverUrl` | string | `https://app.openpush.ai` | code | code |

"Console" means the value saved in the console wins on a Typical site. If your code passes a different value, the SDK ignores it and logs one warning. On Custom code, a site that passes no `prompts` shows no prompt: call `Notifications.requestPermission()` or `Prompts.*` yourself.

- **`welcomeNotification`** is sent by the server once, when a browser first subscribes. It is never sent on a move, a token change or an opt-in again, and never to a person who opted out. On Custom code the title is cut at 60 characters, the message at 150, and the URL must be an `https` address on your site.
- **`allowLocalhost`** lets `http://localhost` and `http://127.0.0.1` work, but only when the app's site address is that localhost origin.
- **`nonce`** is put on the one `<style>` element the prompt UI adds, for sites with a strict Content Security Policy. The SDK uses no `eval` and no inline event handlers.
- **`serverUrl`** changes the OpenPush server. Leave it out unless OpenPush gives you another address, for example for a staging app.

`initialize` resolves once the SDK is ready. At that moment it also fires an `openpush:initialized` event on `window`, with `event.detail` = `{version, subscriptionId}`, for code that loads after the SDK.

**Verify:** with `logLevel: "info"`, the console shows `[OpenPush]` lines and no error. `OpenPush.version` reads `1.1.0`.

## Step 5 — identity

```js
OpenPush.login("user-7");                 // every page load, once the user is known
OpenPush.login("user-7", authHashFromYourServer);
OpenPush.logout();
```

`login` sets the external ID on this browser's subscription. Call it on every page load once you know the user. If the browser has no subscription yet, the external ID rides along with the first registration. `logout` detaches the browser from the user on the server and clears the external ID, tags and aliases kept in this browser.

When the app has identity verification on, pass the hash your server computed: `HMAC-SHA256(external_id)` keyed with a REST API key, as lowercase hex. Never compute it in the page. If you call `login` without a hash, the SDK asks your handler for one:

```js
OpenPush.onIdentityVerificationRequired(async (externalId) => {
  const res = await fetch(`/api/openpush-hash?user=${encodeURIComponent(externalId)}`);
  return res.ok ? (await res.json()).hash : null;   // null stays anonymous
});
```

`OpenPush.User.externalId` reads the current external ID. `User.addObserver(fn)` fires on login, on logout and when the browser gets its subscription id, with `{previous: {externalId, subscriptionId}, current: {…}}`. See [users-and-subscriptions.md](users-and-subscriptions.md).

## Step 6 — tags, aliases and language

```js
OpenPush.User.addTags({ plan: "pro", topic_news: "1" });
OpenPush.User.removeTag("trial_expiry");

OpenPush.User.addAlias("crm_id", "c-88");
OpenPush.User.removeAlias("crm_id");

OpenPush.User.setLanguage("fr");          // overrides the browser's language
```

- Tag keys are letters, digits, `_`, `-` and `.`, up to 60 characters. Values are up to 300 characters and are stored as text. A bad key throws `invalid_argument`.
- Tags, aliases and the language ride the next registration, as in the mobile SDKs. Several writes in a row become one request.
- `getTags()` returns this browser's copy of the user's tags. The copy refreshes from the server each time the browser registers (on page load and at `login()`), unless a tag change made here is still on its way. `login()` as a different user and `logout()` start it empty.
- The alias label `external_id` is reserved. The server keeps at most 10 aliases per user.

## Push subscription and permission

`OpenPush.PushSubscription` (also `OpenPush.User.pushSubscription`) describes this browser:

| Member | Meaning |
|---|---|
| `id` | The OpenPush subscription id, or `null` until the server first accepts this browser |
| `token` | The browser's push endpoint |
| `optedIn` | `true` only when permission is granted, the browser has a push subscription, and the person has not opted out |
| `status` | One of the values in the table below |
| `snapshot()` | `{id, token, optedIn, status}` at this moment |
| `optIn()` | Turns push back on after an opt-out. Asks for permission when needed |
| `optOut()` | Stops pushes to this browser (`status -2`). Keeps the browser's subscription, so `optIn()` needs no new prompt |
| `addObserver(fn)` | Fires with `{previous, current}` on a new token, a new id, an `optedIn` change, and a permission change made in browser settings. `addChangeObserver` is the same |

| Browser permission | Push subscription | Opted out | `status` |
|---|---|---|---|
| any | push not supported | — | `"unsupported"` |
| not asked yet | none | — | `"not_asked"` |
| blocked | none | — | `"denied"` |
| allowed | being created | — | `"pending"` |
| allowed | yes | no | `"subscribed"` |
| allowed | yes | yes | `"opted_out"` |

`OpenPush.Notifications` gives the permission itself:

| Member | Meaning |
|---|---|
| `permission` | `true` when the browser allows notifications for your site. It ignores an opt-out |
| `permissionStatus` | The browser's own value: `"default"`, `"granted"` or `"denied"` |
| `canRequestPermission` | `true` while the browser has not been asked and push is supported |
| `isPushSupported()` | `false` in browsers without push, in in-app browsers, and in iPhone and iPad tabs |
| `requestPermission()` | Shows the browser's prompt, then subscribes. Resolves `true` when allowed. Call it from a click or tap |
| `addPermissionObserver(fn)` | Fires with `{permission, status}`, also for a change made in browser settings |

```js
document.querySelector("#notify").addEventListener("click", async () => {
  const allowed = await OpenPush.Notifications.requestPermission();
});
```

Firefox, Safari, iPhone and iPad Home Screen apps, and Chrome on Android show the browser's prompt only after a click or tap. Call `requestPermission()` directly from the click handler, before any other `await`.

**An opt-out is final until the person acts.** When someone opts out (with `optOut()`, a prompt's Unsubscribe, or from the console or the API), the server keeps the browser opted out. Only a choice the person makes on the page brings it back: `optIn()`, a tap on Allow or Subscribe in an OpenPush prompt, or allowing the browser prompt that `requestPermission()` showed. Page loads, auto resubscribe and token changes never undo an opt-out.

**Auto resubscribe** (`autoResubscribe`, on by default) repairs a browser that still allows notifications but has lost its push subscription, for example after the person cleared site data. It runs on page load without a prompt and never undoes an opt-out.

## Prompts

On a Typical site you build prompts in the console, and the SDK shows them. On Custom code you pass them to `initialize`. There are five types:

| Type | What it shows |
|---|---|
| `slide_in` | A slide-in prompt with your message, Allow and Later. With topics on, a list of up to 10 topics, each saved as a tag (`"1"` checked, `"0"` not) |
| `bell` | A bell in a corner of the page. It opens a small panel to subscribe or unsubscribe |
| `button` | A button you place on your page. Paste `<div data-openpush-button="footer"></div>` where it should appear |
| `browser` | The browser's own prompt. Where a browser needs a click first, the SDK shows the slide-in first and asks from its Allow |
| `email_phone` | Fields for an email address, a phone number or both, with a consent line. Needs the app's Email channel or texting set up |

```js
await OpenPush.initialize({
  appId: "your-app-id",
  prompts: [
    {
      id: "news",
      type: "slide_in",
      enabled: true,
      timing: { auto: true, page_views: 2, seconds: 10 },
      topics: {
        enabled: true,
        items: [
          { tag: "topic_news", label: "News" },
          { tag: "topic_offers", label: "Offers" },
        ],
      },
      wording: { en: { message: "Get news from us?", allow: "Allow", later: "Later" } },
    },
    { id: "bell", type: "bell", enabled: true, position: "bottom-right", size: "medium" },
  ],
});
```

- **Timing** is page views AND seconds on this page: both must be met. With `auto: false`, a prompt shows only when your code calls it (the bell and buttons are always on the page).
- **One at a time.** When several automatic prompts are due, one shows per page load, in this order: `browser`, `slide_in`, `email_phone`.
- **After Later or close,** the same prompt waits 3 days, then 7 days after a second dismiss, then 30 days.
- **People who opted out** never get an automatic push prompt again. The bell or a button is their way back.
- **Wording** has defaults in English, Spanish, Portuguese (Brazil), French, German, Italian, Japanese, Korean, Chinese (Simplified), Hindi, Indonesian, Turkish, Russian and Arabic, chosen by `promptsLanguage`. Messages are up to 90 characters, button labels up to 20 and consent lines up to 300.
- **Look:** prompts use your site icon, a neutral style and the visitor's system font. They render in a shadow root, so your CSS does not change them and theirs does not leak into your page. Colours are the only style options. The placed button has classes for your CSS: `openpush-button`, `openpush-button--subscribed`, `openpush-button--unsubscribed`, `openpush-button--link` and `openpush-button--small|medium|large`.

Show a prompt from code, for example from a "Get notified" link. `force: true` skips the timing and the wait after a dismiss, so call it from a click:

```js
link.addEventListener("click", () => OpenPush.Prompts.showSlideIn({ force: true }));
```

`Prompts.showSlideIn`, `showTopics`, `showEmail`, `showPhone`, `showEmailOrPhone` and `showBell` take the same `{force}` option. `Prompts.addListener(event, fn)` reports `shown`, `accepted` (Allow, Subscribe or submit), `dismissed` (Later or close; counts for the wait) and `closed` (gone without a choice, for example on navigation), each with `{type, promptId}`.

**The email or phone prompt** records the consent line it showed with the address. An email address is added at once. A phone number gets a text with a code first and is subscribed only after the code is right. The prompt shows the same confirmation whether or not an address was known, and it never changes an address or number that unsubscribed or was blocked.

## Notifications and events

| Listener | Payload | Fires |
|---|---|---|
| `Notifications.addClickListener(fn)` | `{notification, result: {actionId, url}}` | On every open page of your site after a click. `actionId` is `""` for a click on the body. When the click opened a new page, it fires there after `initialize` |
| `Notifications.addForegroundLifecycleListener(fn)` | `{notification, preventDefault(), display()}` | On the focused page, before the notification shows |
| `Notifications.addDismissListener(fn)` | `{notification}` | When the person closes it. Safari does not report closes |

Each has a matching `remove…` method. The `notification` object has `id` (the message id), `title`, `body`, `icon`, `image`, `badge`, `url`, `buttons` (`[{id, title, url, icon}]`, at most 2), `topic`, `data` (the message's custom data) and `receivedAt`.

```js
OpenPush.Notifications.addForegroundLifecycleListener((event) => {
  if (location.pathname === "/inbox") {
    event.preventDefault();            // the page shows it its own way
    showInPageBanner(event.notification);
  }
});
```

`preventDefault()` works in Chrome, Edge and Firefox, where a focused page may skip a notification. Safari always shows it, because Safari stops push for sites that receive a push without showing it.

**Click behaviour.** A click opens the clicked button's link, else the message's web link, else `defaultUrl`, else your site. `clickBehavior` (or the console's Click behaviour section) decides which open window is reused:

| `match` | `action` | What happens |
|---|---|---|
| `exact` | `navigate` (default) | A window whose address is exactly the link is focused and loaded again. Otherwise a new window opens |
| `origin` | `navigate` | Any window on your site is focused and goes to the link. Otherwise a new window opens |
| `exact` | `focus` | A window whose address is exactly the link is focused, not reloaded. Otherwise a new window opens |
| `origin` | `focus` | Any window on your site is focused, not reloaded. Otherwise a new window opens |

A link on another site always opens a new window. A link with `op_open=0` in its query closes the notification and opens nothing, for buttons that only record a choice (Safari always opens). Phones may not bring a window forward from a click; the click is still recorded.

**Other members:** `Notifications.setDefaultUrl(url)` and `setDefaultTitle(title)` set the defaults for pushes without a link or a title. `clearAll()` closes your site's notifications. `remove(topic)` closes the one with that topic.

**Receipts are automatic.** The worker reports when a push arrives, when it is shown, when it is clicked and when it is closed. Message reports show Delivered (the push service accepted it), Confirmed Receipt (the worker received it), Notification displayed and Clicked. Closes go to [Event Streams](data-connections.md) as `message.push.dismissed` and are not a report metric.

## Webhooks on your own server

The worker can tell your own server when a notification is shown, clicked or closed. Set the URLs in the console's Advanced section, or in `webhooks` on Custom code. They must be `https`, and visitors can see them in your page's config.

```js
webhooks: {
  displayed: "https://api.example.com/push/displayed",
  clicked: "https://api.example.com/push/clicked",
  dismissed: "https://api.example.com/push/dismissed",
  cors: false,
}
```

The worker POSTs JSON:

```json
{
  "event": "notification.clicked",
  "message_id": "msg_01hq7n8v5r",
  "title": "Your order shipped",
  "body": "Tap to track it",
  "data": {"order": "A-1042"},
  "url": "https://www.example.com/orders/A-1042",
  "action_id": ""
}
```

`event` is `notification.displayed`, `notification.clicked` or `notification.dismissed`. `action_id` is only on clicks (`""` for the body).

- With `cors: false` (the default), the request is sent as `text/plain` with no preflight, and your page cannot read the answer.
- With `cors: true`, it is sent as `application/json` with an `X-OpenPush-Event` header and the `subscription_id` in the body. Your server must answer the CORS preflight.
- Each event is sent once, with no retry. Duplicates are possible, so deduplicate on `message_id` plus `event`. Safari sends no `dismissed`.

## Phone numbers and email addresses

```js
OpenPush.User.addEmail("ana@example.com");
OpenPush.User.removeEmail("ana@example.com");

const v = await OpenPush.Verify.start("+447700900123");
// ask the person for the code they received
await OpenPush.Verify.check(v, "123456");
OpenPush.User.addSms("+447700900123");
```

These work as in the mobile SDKs, and also in browsers without push. An email address is added for the logged-in user unless it unsubscribed or was blocked. A phone number for texts or WhatsApp (`addSms`, `addWhatsApp`) receives nothing until a phone code proves it. `Verify.start(phone, channel?, locale?)`, `check` and `resend` drive phone codes for your own UI. See [email.md](email.md) and [sms-whatsapp.md](sms-whatsapp.md).

## Sessions, events and outcomes

```js
OpenPush.trackEvent("checkout_started", { cart_value: 42 });
OpenPush.Session.sendOutcome("purchase", 19.99);
OpenPush.Session.sendUniqueOutcome("signed_up");
```

- **Sessions** are counted for you. A new session starts when a page loads or a tab becomes visible more than a minute after the site was last seen. All tabs share one session. A session's length is sent when the next session starts. Sessions feed segments and [best-hour delivery](best-hour-delivery.md).
- **Events** go in batches of up to 50, every 5 seconds. Each event carries the browser, the OS and the SDK version. See [events.md](events.md).
- **Outcomes** are custom events. `sendUniqueOutcome(name)` counts once per push that led the person here (the last push they clicked or received within 24 hours), or once a day without one.

Only browsers with a subscription send sessions.

## Consent and privacy

To hold the SDK until the person agrees:

```js
OpenPush.setConsentRequired(true);       // before initialize
await OpenPush.initialize({ appId: "your-app-id" });
// later, when the person agrees:
OpenPush.setConsentGiven(true);
```

While consent is required and not given, the SDK stores nothing and sends nothing. Calls made meanwhile run once consent is given. `setConsentGiven(false)` stops all later writes; data already on the server stays. You can also pass `requiresConsent: true` to `initialize`.

**What a registration sends:** the platform (`web`), the push subscription (endpoint and keys), the browser and OS with their versions, whether the site runs as an installed app, the language, the timezone, a country derived from the timezone, the SDK version, the status, and the external ID, tags and aliases you set. The SDK does not collect an IP address, a location or an advertising ID.

**What the SDK stores in the browser** (no cookies), for your cookie and privacy policies:

| Where | Name | Contents |
|---|---|---|
| IndexedDB | `openpush-web-sdk` | Store `cfg`: the app, server and push settings, this browser's subscription id, endpoint and device secret. Store `state`: external ID, tags, aliases, language, opt-out and consent. Store `queue`: writes waiting to be sent. Store `clicks`: the last click, for 60 seconds |
| localStorage | `openpush.prompts` | Page views, and when each prompt may show again |
| localStorage | `openpush.session` | Session start and active time |
| localStorage | `openpush.debug` | The log level |
| localStorage | `openpush.web.v1` | Written by the old web SDK (Firebase). Read to move the browser. Kept until the browser has moved |

Clearing site data removes all of it. The next visit then creates a new subscription; the old one is found dead at the next send.

## Debug and errors

```js
OpenPush.Debug.setLogLevel("trace");     // kept for later page loads; reaches the worker too
OpenPush.Debug.addLogListener(({ level, message, at }) => myLogs.push(message));
```

Add `?openpush_debug=trace` to a page address to see everything for that visit without saving it. Log lines start with `[OpenPush]`. They never contain the SDK key, push keys, full endpoints, full email addresses or full phone numbers.

Every rejection is an `OpenPushError` with a `code`:

| Code | When | What to do |
|---|---|---|
| `not_initialized` | A call that needs `initialize` came first | Call `initialize`, or push your code to `OpenPushDeferred` |
| `invalid_argument` | A bad value, for example a tag key with a space | Fix the value |
| `not_supported` | No push in this browser. `detail.reason`: `no_push_api`, `in_app_browser`, `ios_needs_home_screen`, `private_mode` | Nothing to fix; hide your push button. Email and phone still work |
| `insecure_origin` | The page is not HTTPS | Serve the site over HTTPS, or use `allowLocalhost` for local testing |
| `wrong_origin` | The page's address is not the app's site address | Use the address set in the console. `www` and no `www` are different |
| `web_push_off` | Web push is turned off for the app | Turn it on in the console |
| `consent_required` | Consent is required and not given | Call `setConsentGiven(true)` when the person agrees |
| `permission_denied`, `permission_dismissed` | The person blocked or closed the browser prompt | Respect it. The bell or a button is the way back |
| `worker_registration_failed` | The worker file could not be registered. `detail.reason`: `not_found`, `not_javascript`, `redirected`, `forbidden`, `scope_not_allowed`, `other` | Check Step 3: the file's address, its type, no redirect, and the scope |
| `worker_scope_taken` | Another service worker already uses that scope | See [Coexisting with a PWA worker](#coexisting-with-a-pwa-worker) |
| `config_unavailable` | The app's web config could not be loaded and none was cached | Check the app id and that the console setup is finished |
| `rate_limited`, `network` | The server or the network refused for now | Nothing; writes are retried |
| `identity_rejected` | The server did not accept the external ID hash | Check how your server computes the hash |

**Writes and retries.** Every server write waits in one queue, in order. A network failure, a 429 or a 5xx is retried after 2 seconds, 8 seconds, then every 30 seconds while the page is open, and the queue is sent again on the next page load. Other 4xx answers drop the write with a log line.

## Browser support

| Browser | Receives push | Large image | Buttons | Badge | Keep on screen |
|---|---|---|---|---|---|
| Chrome and Edge on Windows, ChromeOS | yes, also with the browser closed | yes | yes | — | yes |
| Chrome and Edge on Android | yes, also with the browser closed | when expanded | yes | yes | — |
| Chrome and Edge on macOS | while the browser runs | — | in an "Options" menu | — | yes |
| Firefox (computers and Android) | while the browser runs (computers) | — | — | — | — |
| Safari 16.4+ on macOS | yes, through macOS | — | — | — | — |
| Safari on iPhone and iPad 16.4+ | as a Home Screen web app only | — | — | — | — |

- **Icon:** Chrome, Edge and Firefox show the push icon; Chrome on macOS shows it as a thumbnail on the right. Safari always shows your site icon. The composer can set a different icon for Firefox.
- **Missed pushes** wait until the message's time to live runs out (3 days by default for websites, 28 days at most).
- **Private windows:** Firefox private windows have no push, and Chrome incognito blocks the prompt. A failed subscribe there is reported as `not_supported` with `private_mode`, does not count as a dismiss, and the SDK does not ask again in that visit.
- **In-app browsers** (the browser inside a social or messaging app) cannot subscribe. Push prompts stay hidden there; the email or phone prompt still works.
- **Background data:** browsers must show every push, so data-only messages are not sent to websites. They are skipped and counted as "Background data is not shown in browsers".
- **Size:** a website push carries about 4 KB in all. Title and body are shortened to fit. Keep custom data under 2 KB.

## iOS and iPadOS: Home Screen web apps

On iPhone and iPad, web push works only when a person has added your site to the Home Screen and opened it from there, on iOS or iPadOS 16.4 or later. In a Safari, Chrome, Edge or Firefox tab, `isPushSupported()` is `false` and no push prompt shows.

1. **Add a web app manifest.** Link it from every page with `<link rel="manifest" href="/manifest.webmanifest">`. It must be on your site and set `display` to `standalone` or `fullscreen`:

   ```json
   {
     "name": "Example",
     "short_name": "Example",
     "start_url": "/",
     "scope": "/",
     "display": "standalone",
     "icons": [
       {"src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png"},
       {"src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png"}
     ]
   }
   ```

2. **Add a Home Screen icon:** `<link rel="apple-touch-icon" href="/icons/apple-touch-icon-180.png">` (180 × 180).
3. **Ask from a tap.** In a Home Screen app the browser prompt appears only after a tap, so the `browser` prompt type shows the slide-in first and asks from its Allow.
4. **Help people add the site.** The slide-in has an option to show short add-to-Home-Screen steps on iPhone and iPad tabs instead of Allow. "Not now" uses the same wait as Later.
5. **"Don't Allow" is final** for that Home Screen app until the person removes it and adds it again. The SDK reports `denied`.
6. **Use the same address.** The manifest's `start_url` and `scope` must be on the app's site address, `www` included or not, as set in the console.

The console's Verify step reports the manifest as a note. It never blocks setup.

To test: open the site in Safari on an iPhone with iOS 16.4 or later, choose **Share › Add to Home Screen**, open the site from the new icon, tap Allow, then send yourself a test push from the console. On iOS the SDK registers one worker per scope, so a site that already has a worker should combine (below).

## Coexisting with a PWA worker

A site has one service worker per scope. If your site already has one (for example for offline pages), choose one of two setups:

- **Separate scope** (recommended when your worker is at `/`): put `openpush-sw.js` in a folder that serves no pages, for example `/openpush/openpush-sw.js` with scope `/openpush/`. Set the path and scope in the console's **Put the file somewhere else**, or in `serviceWorkerPath` and `serviceWorkerScope` on Custom code. Your worker keeps `/`.
- **Combined:** add the `importScripts` line to your existing worker and set that file as the worker path. OpenPush then handles only its own pushes; your own push code keeps working for everything else. Pushes from OpenPush carry the key `op_v` in their data, so your own `push` handler can skip them.

On iPhone and iPad, combine.

The SDK never replaces another worker at the same scope. If one exists with a different file, the SDK does not register, logs both paths and reports `worker_scope_taken`. A worker at a parent scope (yours at `/`, OpenPush at `/openpush/`) is fine. Code that unregisters every service worker also removes OpenPush's.

## Changing the worker location

- **Change only the scope when you can.** A scope above the file's folder needs your server to send a `Service-Worker-Allowed` header with the file, for example `Service-Worker-Allowed: /` for `/openpush/openpush-sw.js` with scope `/`.
- **When you move the file,** keep the old file online for at least 12 months, with a comment such as `// keep until 2027-12-01`. Browsers that have not visited since the move still load the old file to show pushes.
- Change the path in the console (or in code on Custom code) at the same time as you deploy the new file.

## Keep permission healthy

Browsers quietly hide or block prompts for sites people often ignore or block, and Chrome may take back permission from sites that send unwanted pushes.

- Use a soft prompt (the slide-in, the bell or a button) with timing, not the browser prompt on the first page view. The console warns when the browser prompt is set to show before 2 page views or 10 seconds.
- Ask when the person has a reason to say yes, for example after reading an article or placing an order.
- Send pushes people want. Avoid copy that looks like an ad.
- Watch how many visitors block notifications. The settings page shows the subscriber count.

## Recipes

**Tag at subscription.** Record where a person subscribed:

```js
OpenPush.PushSubscription.addObserver(({ previous, current }) => {
  if (!previous.optedIn && current.optedIn) {
    OpenPush.User.addTag("subscribed_on", location.pathname.slice(0, 300));
  }
});
```

**A/B test a prompt.** On Custom code, pick a group once, store it in a tag, and pass a different prompt per group:

```js
let group = localStorage.getItem("prompt_test");
if (!group) {
  group = Math.random() < 0.5 ? "a" : "b";
  localStorage.setItem("prompt_test", group);
}
OpenPush.User.addTag("prompt_test", group);
await OpenPush.initialize({
  appId: "your-app-id",
  prompts: [group === "a" ? slideInWithTopics : bellOnly],
});
```

Compare opt-ins with two segments on the `prompt_test` tag.

**A preference centre.** On a settings page, map your own checkboxes to tags with `User.addTags` and `User.removeTags` (or place the slide-in with topics), offer `PushSubscription.optIn()` and `optOut()`, add an email address with `User.addEmail`, and place a button prompt. Send to segments on those tags. See [segments.md](segments.md).

## Limits

- No send API in the SDK. Sending is REST, MCP or console only.
- One site address per app. Several origins, HTTP sites and subdomain relays are not supported.
- No web push to browser extensions, no in-app messages, Live Activities or VoIP on the web, and no legacy Safari push for macOS 12 and earlier.
- Every push goes through the worker. Safari's push without a worker is not used.
- At most 2 buttons per push, and only browsers that show buttons show them.
- Tag values are text.

## Upgrading from the old web SDK (Firebase)

The old web SDK (Firebase), OpenPush's first web snippet, delivered through Firebase. The Web SDK does not use Firebase.

1. Replace the old script and its setup code with the snippet in Step 2. If you called `init`, `requestPermission`, `login`, `logout`, `getSubscriptionId` or `onClick`, those names still work.
2. In your worker file, replace the old `importScripts` line with the one in Step 3. Keep the file's name and path.
3. Remove the Firebase web app config from your page. OpenPush no longer needs it.

Browsers that subscribed through the Firebase web SDK move on their next visit, with no prompt. They keep the same subscription in OpenPush, so their tags, user and external ID stay, as long as the old SDK had saved the subscription id in that browser. Without it, the browser registers as a new subscription, and your next `login()` links it to the user. Until a browser visits, it keeps receiving through the old Firebase path.

What changes: `logout()` now detaches the browser from the user on the server, not only in the page. `onBackground` never fires, because browsers do not receive data-only pushes.

OpenPush can also serve the Web SDK from the old SDK's addresses for your workspace, with the old calls still working: the upgrade bridge. Sites then move with no code change at all. Ask support to turn this on.

The link code is not sent by the Web SDK or by the upgrade bridge: `requestPermission({linkCode})` logs a warning and sends none. A site that links browsers with link codes should keep the Firebase web SDK, or move to `login()`.

The Firebase path stays for 12 months after direct web push launches. After that date, browsers that never moved are skipped at send time ("Browser not moved to direct web push") and kept, so they can still move if they visit later.

<!-- verify: phase 10 -->

## Moving from another web push provider

A site that used another provider's web SDK can switch by changing two lines: the script tag and the worker's `importScripts` line. A compatibility layer accepts that SDK's calls. Browsers move on their next visit with no prompt. The migration guide, under **Start here** in the docs menu, covers the details.

## Troubleshooting

**Delivered but not shown.** The report says Delivered or Confirmed Receipt, but nothing appears.

- Check the operating system's notification settings for the browser: Windows notifications, macOS **System Settings › Notifications** for the browser, Android's notification settings for the browser and the site, and on iPhone and iPad **Settings › Notifications** for the Home Screen app.
- Check Focus and Do Not Disturb.
- Check the site's permission in the browser (the icon left of the address bar).
- On macOS, Chrome, Edge and Firefox must be running to receive.

**Hosts to allow.**

- A strict Content Security Policy needs `script-src https://app.openpush.ai` (this also covers the worker's `importScripts`), `connect-src https://app.openpush.ai`, and `worker-src 'self'`.
- A firewall must let browsers reach the push services: `fcm.googleapis.com`, `*.push.services.mozilla.com`, `web.push.apple.com` and Apple's push hosts (`*.push.apple.com`, TCP 443 and 5223), and `*.notify.windows.com`.

**Corporate networks** sometimes block push services. A browser can then subscribe but never receive. Test from another network.

| Symptom | Cause | Fix |
|---|---|---|
| The console's Verify step says the script is not found | The page does not load the SDK, or the SDK is bundled | Open the site once in a browser; a bundled SDK passes once it has loaded the app's config |
| The Verify step says the worker is not found, or is served as a web page | No file at that path, or the server returns your HTML page for unknown paths | Put `openpush-sw.js` at the path shown, served as JavaScript |
| `worker_registration_failed` with `redirected` | The worker URL redirects, for example to add `www` | Serve it from the exact site address, with no redirect |
| `wrong_origin` in the log | The page is on another address than the app's site | Use the address set in the console |
| `worker_scope_taken` in the log | Your site already has a worker at that scope | Use a separate scope, or combine |
| Nothing happens on iPhone | The site is open in a tab | Add it to the Home Screen and open it from there |
| The prompt does not show | Timing not met, a recent dismiss, an opt-out, an in-app browser, or Custom code with no `prompts` | Use `?openpush_debug=trace` to see why |
| Pushes stopped for one browser after a long time | The person cleared site data, or the browser dropped the subscription | The next visit subscribes again with auto resubscribe |
| The settings page says pushes can't reach your site's browsers | A check of your site failed, or the push services refused OpenPush's sends | Read the reason on the page, fix it, then press Check again |

## FAQ

**Do I need Firebase?**
No. OpenPush sends to browsers directly with standard Web Push and its own key pair for your app.

**Do I need to copy a key into my page?**
No. The page needs only your app id. The SDK reads the public SDK key from the app's web config.

**Can I use one OpenPush app for two sites?**
No. One site address goes to one app. Two apps on the same site would each move the browser to their own key on every visit, so pushes would keep breaking. The SDK logs a warning when it finds a subscription stored for another app. Use one app per site; `www` and no `www` are different sites.

**Does the welcome notification go to everyone again after an update?**
No. It goes once per browser, when it first subscribes.

**Is the SDK key safe in the page?**
Yes. It can register browsers and post receipts and events, nothing else.

**What happens when I turn web push off?**
No website subscriber receives anything, through either path, and no prompt shows. Subscribers are kept. Turning it on again restores everything.

## Support and security

Report a vulnerability to `security@openpush.ai`; see the [vulnerability disclosure policy](https://www.openpush.ai/vdp). For product support, write to `support@openpush.ai`.

## Related

- [web-push.md](web-push.md)
- [quickstart.md](quickstart.md)
- [users-and-subscriptions.md](users-and-subscriptions.md)
- [sending-messages.md](sending-messages.md)
- [segments.md](segments.md)
- [events.md](events.md)
- [email.md](email.md)
- [sms-whatsapp.md](sms-whatsapp.md)
- [security-and-limits.md](security-and-limits.md)
- [../api-handbook/03-subscriptions-users.md](../api-handbook/03-subscriptions-users.md)
- [../api-handbook/06-events-ingest.md](../api-handbook/06-events-ingest.md)
