Web Push SDK (JavaScript)

notifysphere-web on npm. Collect web push subscribers on your website and send them notifications from the dashboard or the REST API, with delivery and click tracking, images and up to two buttons.

Prerequisites#

  • A notifySphere app with your Firebase service account JSON uploaded. See Push setup and Firebase credentials.
  • In the same Firebase project: a Web app (Project settings → General → Add app → Web). Copy its config: apiKey, projectId, messagingSenderId and appId.
  • A Web Push certificate (Project settings → Cloud Messaging → Web Push certificates → Generate key pair). The public key is your vapidKey. Firebase keeps the private key, so you don't need our VAPID key generator for this setup.
  • Your site on https. http://localhost also works while you test.

Install#

With a bundler (React, Next.js, Vue, Angular, Vite):

bash
npm install notifysphere-web

Without a bundler (plain HTML, WordPress, Shopify themes), load it from a CDN:

html
<script src="https://cdn.jsdelivr.net/npm/notifysphere-web@0.1.0/dist/notifysphere.js"></script>

The script tag gives you a global NotifySphere object. An ES module build is also on the CDN at dist/notifysphere.mjs.

Setup#

  1. Serve the service worker from your site's root

    Download notifysphere-sw.js (also in the npm package at notifysphere-web/dist/notifysphere-sw.js) and serve it so it loads from https://yoursite.com/notifysphere-sw.js. In Next.js or Vite, put it in the public/ folder.

    Already have a service worker, for example for a PWA? Add one line to it instead:

    js
    // At the top of your existing service worker
    importScripts('/notifysphere-sw.js');
  2. Initialize the SDK

    init() registers the service worker. It never shows a permission prompt, so it's safe to call on every page load.

    import NotifySphere from 'notifysphere-web';
    
    NotifySphere.init({
      appId: 'YOUR_NOTIFYSPHERE_APP_ID',
      vapidKey: 'YOUR_WEB_PUSH_PUBLIC_KEY',
      firebase: {
        apiKey: 'YOUR_FIREBASE_WEB_API_KEY',
        projectId: 'your-project',
        messagingSenderId: '000000000000',
        appId: '1:000000000000:web:0000000000000000',
      },
    });
    
    // Ask for permission from a click, never on page load
    document.querySelector('#notify-me').addEventListener('click', () => {
      NotifySphere.subscribe();
    });
  3. Ask for permission at the right moment

    Chrome and Firefox hide or block permission prompts that appear on page load. Ask after a click: call subscribe() from your own button, or show a small card with showPrompt(). The browser prompt opens only after the visitor clicks Allow on the card, and "Not now" hides it for 3 days.

    js
    NotifySphere.showPrompt({
      title: 'Get order updates',
      message: 'We will only notify you about your orders.',
    });
  4. Visitors are subscribed anonymously at first. After login, call identify() so you can target this person by user ID, email or tags.

    js
    // After your user logs in
    await NotifySphere.identify({ id: 'user_123', name: 'Jane Doe', email: 'jane@example.com' });
    
    // Tags for segments. null removes a tag
    await NotifySphere.setTags({ plan: 'pro', trial: null });
    
    // On logout: the browser keeps getting pushes as an anonymous visitor
    await NotifySphere.logout();

Send a web push#

Web subscribers get the campaigns you send from the dashboard and the REST API, the same way as mobile devices. See Campaigns.

  • Title, message, icon and a large image are shown.
  • Up to 2 action buttons.
  • A click on the notification opens your site. To open a specific page, add a button whose id is that page's URL. Only http and https links are opened.

Delivery and click tracking#

The service worker reports delivery as soon as the notification is shown, and reports a click with the id of the button that was pressed. Both appear in the campaign's Delivered and Clicked numbers in the dashboard.

API reference#

init(options)#

FieldTypeRequiredDescription
appIdstringYesYour notifySphere App ID
firebaseobjectYesFirebase web app config: apiKey, projectId, messagingSenderId, appId
vapidKeystringYesPublic key of your Firebase Web Push certificate
serviceWorkerPathstringNoWhere the service worker is served (default /notifysphere-sw.js)
serviceWorkerScopestringNoService worker scope (default /)
debugbooleanNoLog what the SDK does to the browser console

Methods#

FieldTypeDescription
subscribe()-Asks for permission (call it from a click) and registers the browser. Returns the subscription ID, or null if the visitor declined.
showPrompt({ title, message })-Shows a small card first, then the browser prompt after the visitor clicks Allow.
unsubscribe()-Stops pushes to this browser.
identify({ id, name, email, phone, city, state })-Links this browser to your user. id is required.
setTags(tags)-Adds or changes tags. A null value removes a tag.
logout()-Detaches the user. The browser stays subscribed as an anonymous visitor.
getSubscriptionId()-The notifySphere subscription ID of this browser.
getPermission()-default, granted or denied.
isSupported()-Whether this browser and page can receive web push.

Browser support#

  • Chrome, Edge, Firefox and Opera on desktop and Android.
  • Safari on macOS 13 and newer.
  • iPhone and iPad (iOS 16.4 and newer) only when the visitor has added your site to the Home Screen.

During the beta, Chrome on desktop is the browser we have tested end to end.

Verify the integration#

  1. Open your site, click your subscribe button and choose Allow. With debug: true the console logs the subscription ID.
  2. Send a test notification from the dashboard. The campaign's Delivered count should go up.
  3. Click the notification. Your site opens and the Clicked count goes up.

Stuck or something unclear? Contact us and we'll help.