Sign up

notifications

How to Implement Web Push Notifications?

Josue Montano

Last updated on

Web push notifications are powered through service workers. A service worker is just a script that your browser runs in the background. By using service works, you can send web push notifications to your users even when they don't have your application open in a tab.

There are some differences in how modern browsers implement this feature. At MagicBell we have created abstractions to hide the complexity so you can enable web push notifications without breaking a sweat.

Step 1: Enable the web push channel

Make sure you have enabled the web push channel for your MagicBell project from the admin UI.

https://app.magicbell.com

Step 2: Create the service worker file

Create the service worker file, make sure this file is available at https://your-domain.com/service-worker.js.

The location of the service worker file is important, it defines the scope of the service worker.

If you use Ruby on Rails, create that file under the public folder
You’ll be able to register the service worker on localhost. However, if you use another domain to develop, you need HTTPS. As a workaround for Google Chrome, open chrome://flags/#unsafely-treat-insecure-origin-as-secure, enable it, add your domain and relaunch the browser.
Enabling domains for testing service workers locally

Step 3: Import MagicBell’s functionality

Open the service worker file you just created and import MagicBell’s handlers for web push notifications:

importScripts('https://assets.magicbell.io/web-push-notifications/sw.js');
service-worker.js

Step 4: Ask users to enable web push notifications

The latest version of our React library exposes the PushNotificationsSubscriber headless component, you can use it to register the service worker, request the user for permissions and store subscriptions to send browser push notifications.

import { PushNotificationsSubscriber } from '@magicbell/magicbell-react';

function MyComponent() {
  <PushNotificationsSubscriber serviceWorkerPath="/service-worker.js">
    {({ createSubscription }) => (
      <button onClick={registerSubscription}>Enable push notifications</button>
    }
  </<PushNotificationsSubscriber>
}

And that’s it! You have enabled web push notifications for Google Chrome and Firefox. Try creating a notification through our API and let the magic begin...

Web push notifications for Safari

Luckily, Safari is configured by default. There are no extra steps to send web push notifications to Safari browsers. It works out of the box!

Related articles to web push notifications:

Featured Blogposts

Related Blogposts