Beams Web SDK Integration (BETA)

This guide will take you through installing/initializing the Beams Web SDK in your application.

Warning: Beta limitations

This SDK is in Beta therefore there may be breaking changes in the future. In its current form, the SDK has the following limitations:

  • The SDK currently supports Chrome, Firefox, Edge and Opera.
  • Open/delivery tracking is not supported. This will affect Insights and Webhooks.

Create a Service Worker

Already have a Service Worker? Please see the advanced guide on integrating existing Service Workers with Beams.

The browser Push API requires that you handle incoming browser notifications in a Service Worker hosted on your site. The steps to set up a Service Worker for your site are as follows:

  1. Create a file called service-worker.js with the following content:

    1
    importScripts("https://js.pusher.com/beams/service-worker.js");
  2. Upload this file to your site at the following location:

    1
    https://your-site.com/service-worker.js
  3. Open service-worker.js in your browser to verify that it is being served.

  4. The service worker file will only enable push notifications on pages hosted on the same domain. Avoid serving the same page from multiple domains, for example, from both https://pusher.com and https://www.pusher.com.

    Web push notifications only work for full HTTPS websites. The only exception is localhost to ease development.

Install the SDK

NPM/Yarn

If you are using NPM/Yarn to manage your Javascript packages, install the SDK as follows:

  • NPM
  • Yarn
1
npm install @pusher/push-notifications-web

And import it into your application:

1
import * as PusherPushNotifications from "@pusher/push-notifications-web"

Script Tag

If you include JavaScript into your application HTML directly, add the following script tag to the page where you're going to prompt for notifications:

1
<script src="https://unpkg.com/@pusher/push-notifications-web@0/dist/push-notifications-cdn.js"></script>

The SDK will be available in the global scope as PusherPushNotifications

Initialize the SDK

Get your Beams instance ID from the Credentials tab on the dashboard and use the following snippet to initialize the SDK:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
PusherPushNotifications.init({
  instanceId: 'YOUR_INSTANCE_ID',
})
  .then(beamsClient =>
    beamsClient
      .start()
      .then(() =>
        console.log(
          'Successfully registered with Beams. Device ID:',
          beamsClient.deviceId,
        )
      )
  )
  .catch(console.error);

Check your integration

When you run the code, a dialog will appear requesting permission to send notifications. After giving permission, open the browser console and check for a log line that saysSuccessfully registered with Beams. This means that the web SDK has been successfully integrated into your app and the browser is ready to receive notifications 🎉

If a permission prompt does not appear, you may have to enable the notification permission in the top left of your address bar and refresh

Subscribe to an interest

Now that the user's browser is registered, we need a way for Beams to know which notifications should be sent to them. In this guide, we will use Beams Device Interests. Any device subscribed to a given Device Interest will receive notifications published to that interest.

Let's subscribe to the interest hello by adding the lines highlighted below:

PusherPushNotifications.init({
  instanceId: 'YOUR_INSTANCE_ID',
})
  .then(beamsClient =>
    beamsClient
      .start()
      .then(() =>
        console.log(
          'Successfully registered with Beams. Device ID:',
          beamsClient.deviceId,
        )
      )
     .then(() => beamsClient.addDeviceInterest('hello'))
     .then(() => beamsClient.getDeviceInterests())
     .then(interests => console.log('Current interests:', interests))
  )
  .catch(console.error);

You should see Current interests: ["hello"] printed to your browser console.

Send a notification

You are now ready to send a notification. In later steps, you will use one of the Beams server SDKs to send notifications. Before you do that, you can test your implementation by sending a notification via a HTTP request to the Beams API. We will use curl in this example, but you could use an alternative tool that allows you to make HTTP requests.

  1. Start by creating a file called publish-body.json with the request body for the publish.

    JSON

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    {
      "interests": ["hello"],
      "web": {
        "notification": {
          "title": "Hello",
          "body": "Hello, world!",
          "deep_link": "https://www.pusher.com"
        }
      }
    }
  2. Next, run the following curl command.

    Either export your instance ID and secret key as environment variables, or replace the variables in the command. If you don't have those keys from the previous steps, then you can find them on the dashboard.

    bash

    1
    2
    3
    4
    curl -H "Content-Type: application/json" \
         -H "Authorization: Bearer $SECRET_KEY" \
         -X POST "https://$INSTANCE_ID.pushnotifications.pusher.com/publish_api/v1/instances/$INSTANCE_ID/publishes/interests" \
         -d @publish-body.json

    After running the curl command, you should receive a notification in your browser 👏If you don't see the notification, check the troubleshooting section.

Customize your notifications

You may have noticed that clicking the notification opens www.pusher.com. This is configurable by changing the deep_link value in the payload. Change deep_link to a different URL and send a notification. Notice how clicking the notification takes you to that new URL.

The full set of options is described in the payload reference docs.

Send notifications from your server

Now you can send notfications from your backend using one of the Beams server SDKs:

  • PHP
  • Go
  • Node.js
  • python
  • Java
  • Kotlin
  • Ruby
1
2
3
4
5
6
7
8
9
10
11
12
13
$beamsClient = new \Pusher\PushNotifications\PushNotifications(array(
  "instanceId" => "YOUR_INSTANCE_ID_HERE",
  "secretKey" => "YOUR_SECRET_KEY_HERE",
));

$publishResponse = $beamsClient->publishToInterests(
  array("hello"),
  array("web" => array("notification" => array(
    "title" => "Hello",
    "body" => "Hello, World!",
    "deep_link" => "https://www.pusher.com",
  )),
));

Where next?

Anything confusing or missing? We are always looking to improve this documentation so get in touch with us at betterbeams@pusher.com

Troubleshooting

Make sure you are using Chrome, Firefox, Edge or Opera

The Beta SDK currently supports Chrome, Firefox, Edge and Opera.

Clear your browser cache

Ensure that your latest code changes have been loaded in your browser by performing a hard refresh (ctrl/cmd + shift + r)

Check if "Do Not Disturb" is enabled

Go to your OS settings and ensure that the "Do Not Disturb" option is disabled.

Check your browser notification permissions

Go to the settings page in your browser and ensure that the notifications permission is enabled for your site and that browser notifications have not been disabled globally.

Make sure your project is HTTPS / localhost

Web Push requires that every resource on the page where notifications are enabled be served over HTTPS. The only exception is if the site is running on localhost.

Restart your browser

We have found that some browsers sometimes need to be restarted before notification permissions can take effect.