Push Notifications Setup Guide: Web

Chatkit supports browser push notifications using the Web Push protocol. This allows Chatkit users to receive notifications about missed messages even when the application tab is closed.

Whilst in Beta, this feature will only support Google Chrome. Cross browser support will be released before this feature becomes generally available.

Upload or import the Chatkit Service Worker

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/chatkit/service-worker.js");
  2. Upload this file to your site at the following location:

    1
    https://your-site.com/service-worker.js

    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.

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

Configure your Website URL

Chatkit browser notifications arrive when your site is not currently opened in the user’s browser. When these notifications are clicked, a new tab will open with your configured website URL.

Chatkit will not send browser notifications if a base URL has not been configured.

Open the dashboard and navigate to the Push Notifications tab for your Chatkit instance. Here you can configure the Base Website URL which is used to open your chat application when someone clicks on the web push notification. This URL can be http://localhost:<PORT> if you’re developing locally, but it must be https if you’re configuring your production environment.

Enable browser notifications

Once a connection to Chatkit has been successfully established, you can enable push notifications by calling the appropriate method on the CurrentUser object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
chatManager
  .connect()
  .then(currentUser => {
    console.log("Connected as user ", currentUser);

    currentUser.enablePushNotifications()
      .then(() => {
        console.log('Push Notifications enabled');
      })
      .catch(error => {
        console.error("Push Notifications error:", error);
      });

      // Do other great things afterwards ✨
    })
Calling this method will prompt the user for permission to send them notifications if they haven't already provided permission for your site.

This integration step is different if you already have an existing Service worker for your site. Please see the advanced guide on integrating existing Service Workers with Chatkit Web Push

Customise when the user sees push notifications

By default, push notifications are received in these two cases:

  • Tab Open - When the browser tab for your site is open but unfocused (i.e. the user is looking at a different tab).
  • Tab Closed - When the browser tab for your site is closed. This can include when the user has no tabs open at all, but the browser process is still running.

If you want notifications to be shown only when the user has an open tab in the background, then you can pass a config object when enabling push notifications, with the propertyshowNotificationsTabClosed: false.

1
2
3
currentUser.enablePushNotifications({
  showNotificationsTabClosed: false
})

Similarly, if you only want notifications to be shown when the user has no open tabs, you can pass in showNotificationsTabOpen: false.

1
2
3
currentUser.enablePushNotifications({
  showNotificationsTabOpen: false
})

Note: push notifications are never received when the tab for your site is open and in the foreground.

Test your integration

Push notifications will only be sent for messages sent in private rooms, and will only be shown when the test user has no visible tabs. This means that you must use a private room for testing and all tabs/app instances for the test user must be closed or hidden.

Log in to the dashboard and open the Instance Inspector in the "Console" tab. You can use this to send test messages.

If you're not receiving a notification, please read the Troubleshooting section.

Implement on click behaviour

When a user clicks on the notification, your application needs to navigate to the correct Chatkit room. How this is done will depend on your application.

The on click behaviour for notifications is different depending on if the user already has open tabs for the application or not. If the user has no open tabs, a click will cause a new tab to be opened with the deep link described below in Deep link routing, otherwise one of the open tabs will be focussed and a callback will be fired in your application code.

Deep link routing

Deep links are comprised of a base URL and a ck_room_id query parameter:

1
https://<YOUR_BASE_URL>/?ck_room_id=<ROOM_ID>

For example, a client-side JavaScript application could implement this in the following way:

1
2
3
4
5
6
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has('ck_room_id')) {
  const roomID = urlParams.get('ck_room_id');

  // Navigate to correct room in your application
}

On click callback

When the user already has open tabs, clicking on the notification will focus one of these tabs. Optionally, you can also provide an onClick callback to the enablePushNotificationsmethod. This callback will be provided with the ID of the relevant room.

For example:

1
2
3
4
5
6
7
8
currentUser
  .enablePushNotifications({
    onClick: ({ roomId }) => {
      // TODO: Navigate to correct room in your application 🧭
    },
  })
  .then(() => console.log("Push notifications enabled"))
  .catch(err => console.error("Push notifications error:", err))

Disable browser notifications

When a user of your application logs out (or opts out of push notifications) you should call the disablePushNotifications method on your application’s ChatManager:

1
2
3
4
5
6
7
8
9
function onLogOut() {
  chatManager.disablePushNotifications()
    .then(() => {
      console.log('Push Notifications disabled');
    })
    .catch(error => {
      console.log('Push Notifications error:', error);
    })
}

After this method is called, Chatkit will stop sending notifications to this browser instance until enablePushNotifications is called again.

Advanced: Integrating existing Service Workers

This section will show you how to use a custom Service Worker registration with Chatkit. If you are only using Service Workers in your app with Chatkit, please ignore this section.

Import the Chatkit Service Worker in your existing file

Only one service worker per domain can be registered.

If you already have a Service Worker file hosted on your domain you can integrate the Chatkit Service Worker by adding an import line at the top of the file:

1
2
3
importScripts("https://js.pusher.com/chatkit/service-worker.js");

// The rest of your Service Worker code goes here ...

Integrate with the SDK

Next, you need to pass the Service Worker registration object to the Chatkit SDK when enabling push notifications.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
chatManager
  .connect()
  .then(currentUser => {
    console.log("Connected as user ", currentUser);

    // NOTE: The current page MUST be within the scope of your custom
    // Service Worker registration. In this example, the current page would
    // have to be hosted under /chat.
    // For example: https://yoursite.com/chat/index.html
    window.navigator.serviceWorker
      .register("/chat/service-worker.js")
      .then(registration =>
        currentUser
          .enablePushNotifications({
            serviceWorkerRegistration: registration,
          })
          .then(() => {
            console.log('Push Notifications enabled');
          })
          .catch(error => {
            console.error("Push Notifications error:", error);
          })
        );

      // Do other great things afterwards ✨
    })

Troubleshooting

Make sure you are sending messages in a private room

Chatkit only shows notifications for messages sent in private rooms.

Make sure you are using Google Chrome

Whilst in Beta, this feature will only support Google Chrome. Cross browser support will be released before this feature becomes generally available.

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)

Ensure that your test user has no visible tabs

We only show notifications if a user has no visible tabs for your application. Ensure that your test user either doesn’t have any application tabs open, or that all of their open tabs are hidden.

Ensure that your test message is from another user

Chatkit will not send a web push notification for messages authored by the currently logged in user. Make sure you are using another user to send test messages in the Chatkit console when testing web push notifications.

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.

Error: current page not in serviceWorkerRegistration scope

If you are getting this error it means that the service worker registration you are passing to Chatkit has a scope that doesn't match the current page. Learn More.