Keep Reading
If you enjoyed the post you just read, we have more to say!
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.
Make sure you have enabled the web push channel for your MagicBell project from the admin UI.
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.
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.
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');
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() {
return (
<PushNotificationsSubscriber serviceWorkerPath="/service-worker.js">
{({ createSubscription }) => (
<button onClick={createSubscription}>
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...
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: