How to Handle Web Push Notifications in Websites and PWAs


RoBird/Shutterstock.com

Push notifications are a typical sight on the trendy internet. They allow you to talk well timed info to the consumer, even when your website’s not truly open. The consumer’s browser handles incoming push occasions and shows notifications utilizing system UI surfaces just like the Windows Action Center and Android lockscreen.

Implementing Web Push into your website or PWA requires the mixture of two distinct browser APIs. The code liable for subscribing to and receiving notifications makes use of the Push API element of service workers. This code runs regularly in the background and will probably be invoked by the browser when a brand new notification wants to be dealt with.

When an occasion’s obtained, the service employee ought to use the Notification API to truly show the notification. This creates a visible alert through OS-level interfaces.

Here’s an entire information to getting Web Push working in your website. We’ll assume you’ve already obtained a server-side element that may register push subscriptions and ship out your alerts.

The Service Worker

Let’s begin with the service employee. Service staff have a number of roles – they will cache information for offline use, run periodic background syncs, and act as notification handlers. Service staff use an event-driven structure. Once registered by a website, the consumer’s browser will invoke the service employee in the background when occasions it subscribes to are generated.

For Web Push, one core occasion is required: push. This receives a PushEvent object that allows you to entry the payload pushed from the server.

self.addEventListener("push", e => {
 
    const payload = JSON.parse(e.information.textual content());
 
    e.waitUntil(self.registration.presentNotification(
        payload.title,
        {
            physique: payload.physique,
            icon: "/icon.png"
        }
    ));
 
});

The code above units up a service employee able to reacting to incoming push occasions. It expects the server to ship JSON payloads trying like this:

{
    "title": "Title text for the notification",
    "body": "This is the longer text of the notification."
}

When a push occasion is obtained, the service employee shows a browser notification by calling the presentNotification() perform obtainable on its self.registration property. The perform’s wrapped in a waitUntil() name so the browser waits for the notification to be displayed earlier than terminating the service employee.

The presentNotification() perform takes two arguments: the notification’s title textual content and an choices object. Two choices are handed in this instance, some longer physique textual content and an icon to show in the notification. Many other options can be found that allow you to setup vibration patterns, customized badges, and interplay necessities. Not all browsers and working programs help all of the capabilities uncovered by the API.

Complete the service employee aspect of the code by registering it again in your important JavaScript:

if (navigator.serviceWorker) {
    // change with the trail to your service employee file
    navigator.serviceWorker.register("/sw.js").catch(() => {
        console.error("Couldn't register the service worker.")
    });
}

This code ought to run on every web page load. It makes positive the browser helps service staff and then registers the employee file. Browsers will mechanically replace the service employee at any time when the server copy reveals byte variations to the at the moment put in model.

Registering for Push Subscriptions

Now you want to subscribe the browser to push notifications. The following code belongs in your important JavaScript file, exterior the service employee.

async perform subscribeToPush() {
    if (navigator.serviceWorker) {
 
        const reg = await navigator.serviceWorker.getRegistration();
 
        if (reg && reg.pushManager) {
 
            const subscription = await reg.pushManager.getSubscription();
 
            if (!subscription) {
 
                const key = await fetch("https://example.com/vapid_key");
                const keyData = await key.textual content();
 
                const sub = await reg.pushManager.subscribe({
                    applicationServerKey: keyData,
                    userVisibleOnly: true
                });
 
                await fetch("https://example.com/push_subscribe", {
                    technique: "POST",
                    headers: {"Content-Type": "application/json"},
                    physique: JSON.stringify({
                        endpoint: sub.endpoint,
                        expirationTime: sub.expirationTime,
                        keys: sub.toJSON().keys
                    })
                });
 
            }
 
        }
 
    }
}

Then name your perform to subscribe the browser to push notifications:

Let’s stroll by what the subscription code is doing. The first few strains verify for the presence of a service employee, retrieve its registration, and detect push notification help. pushManager gained’t be set in browsers which don’t help Web Push.

Calling pushManager.getSubscription() returns a promise that resolves to an object describing the browser’s present push subscription in your website. If that is already set, we don’t want to resubscribe the consumer.

The actual subscription circulation begins with the fetch request for the server’s VAPID keys. The VAPID specification is a mechanism which lets the browser confirm push occasions are literally coming out of your server. You ought to expose a server API endpoint that gives a VAPID key. This is given to the pushManager.subscribe() perform so the browser is aware of the important thing to belief. The separate userVisibleOnly possibility signifies we’ll solely show notifications that visibly show on the display.

The pushManager.subscribe() name returns a PushSubscription object describing your new subscription. This information is distributed to the server in one other fetch request. In an actual app, you’d additionally ship the lively consumer’s ID so you could possibly hyperlink the push subscription to their gadget.

Your server-side code for sending a push notification to a consumer ought to look one thing like this:

  1. Query your information retailer for all push subscriptions linked to the goal consumer.
  2. Send your notification payload to the endpoint indicated by every subscription, ensuring to embody the subscription’s authentication keys (keys in the info despatched by the browser when subscribing). Sign the occasion with the identical VAPID key you despatched to the browser.

Each subscription’s endpoint will reference the browser vendor’s notification supply platform. This URL already features a distinctive identifier for the subscription. When you ship a payload to the endpoint, the browser’s background course of will ultimately obtain the info and invoke your service employee. For Chrome on Android, the browser course of is straight built-in with the system notification daemon.

When to Subscribe the User?

When organising subscription flows, keep in mind the consumer could have to acknowledge a browser permission immediate earlier than registration completes. Many browsers automatically hide or reject unsolicited permission requests; in any case, asking a consumer to subscribe the second they land in your website could not ship the consequence you need.

You get one of the best likelihood of a profitable sign-up by coupling subscription requests to a direct consumer motion. Consider offering an in-app banner that explains the advantages of enabling notifications and gives an “Enable Now” button. You can verify whether or not the consumer’s already subscribed and disguise the banner with the pushManager.getSubscription() perform proven above.

Clicking the allow button ought to name your subscription perform. The course of might take a couple of seconds whereas the browser units up the registration and your community calls full. Displaying a loading spinner throughout this time will assist preserve the consumer knowledgeable.

Users also needs to be given a method to unsubscribe. Although they will revoke the browser permission at any time, some customers will search for an in-app possibility, particularly in the event that they’ve put in your website as a PWA.

Here’s a easy unsubscribe implementation:

async perform unsubscribePush() {
 
    const reg = await navigator.serviceWorker.getRegistration();
    const subscription = await reg.pushManager.getSubscription();
 
    if (subscription) {
        await subscription.unsubscribe();
        await fetch(`https://instance.com/push_unsubscribe/${subscription.endpoint}`, {technique: "DELETE"});
    }
    else {
        // already subscribed
    }
 
}

Calling unsubscribe() on a PushSubscription cancels the subscription, reverting the browser to its default state. Your service employee will cease receiving push occasions. The subscription’s endpoint is distributed to your server so you may take away it out of your information retailer and keep away from sending information to what’s now a lifeless URL.

Handling Expirations and Renewals

You might need seen the expirationTime property on the PushSubscription object created by the browser. This gained’t all the time be set; when it’s, the gadget will cease receiving notifications after this time.

In follow, expirationTime isn’t at the moment used in main browsers. Tokens produced by Chrome don’t expire till manually unsubscribed so expirationTime is all the time null. Firefox doesn’t set expirationTime both however its notification service can change subscriptions throughout their lifetime.

You can reply to the browser altering your lively push subscription by implementing the pushsubscriptionchange occasion in your service employee. Unfortunately there are two variations of this occasion: the unique implementation, at the moment utilized by Firefox, and the brand new v2, not but supported in any browser.

The authentic spec has critical usability points which make it tough to reply to the occasion. When you obtain a v1 occasion, the browser has deleted the unique subscription and you want to manually create a brand new one. The downside is with out entry to the expired subscription you may’t situation a “replace” request to your server – you’ve obtained no method of accessing the outdated endpoint URL.

The v2 spec solves this by offering an occasion with oldSubscription and newSubscription properties. When you obtain the occasion, the outdated subscription has been canceled however you may nonetheless entry its properties. The new subscription is now created for you by the browser.

Here’s an instance of implementing pushsubscriptionchange with the brand new spec:

self.addEventListener("pushsubscriptionchange", e => {
    e.waitUntil(async () => {
        await fetch("https://example.com/push_change", {
            technique: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            physique: JSON.stringify()
        });
    });
});

Endpoints are distinctive so your server can lookup the outdated subscription and replace its properties with these of the brand new subscription. If you need to add help for the outdated spec too, you’ll want to manually monitor the lively subscription endpoint exterior of the push API. Storing it into localStorage or IndexedDB will allow you to entry it inside your pushsubscriptionchange handler so you may ask the server to change the subscription.

The revised spec is far simpler to implement than its older counterpart. Even although it’s not but supported in browsers, it’s price including it to your service employee anyway. Just a few strains of code will future-proof your push dealing with towards new browser releases.

Adding Action Buttons

Push notifications can embody interactive buttons that permit the consumer take instant actions. Here’s a presentNotification() name which creates one:

self.registration.presentNotification(
    "Notification with actions",
    {
        physique: "This notification has a button.",
        actions: [
            {
                action: "/home",
                title: "Go to Homescreen",
                icon: "/home.png"
            }
        ]
    }
);

Each notification can embody a number of actions, every with a label, icon and motion. The latter property ought to establish an motion your app can provoke in response to the consumer’s press.

When the consumer faucets an motion, your service employee receives a notificationclick occasion:

self.addEventListener("notificationclick", e => {
    const uri = e.motion;
    const notification = e.notification;
    notification.shut();
    shoppers.openWindow(`${self.location.origin}${motion}`);
});

We’re utilizing the motion property to declare a URI the consumer can navigate to. A brand new tab’s opened to the URI when the notification is pressed. Calling notification.shut() ensures the notification is dismissed too. Otherwise, some platforms will make the consumer manually swipe it away.

Summary

Implementing Web Push can appear daunting in case you’ve not labored with the related APIs earlier than. More than the technical issues, it’s best to preserve the consumer expertise on the forefront of your thoughts and ensure you talk why it’s price enabling notifications.

Subscribing and unsubscribing to push happens in your software’s important JavaScript code, utilizing navigator.serviceWorker APIs. The code that responds to new push occasions and shows browser notifications lives in the service employee itself.

Web Push is now supported by most main internet browsers, Safari being the outstanding exception. Remember that notifications will render otherwise in every browser and working system household so don’t assume {that a} specific function of the presentNotification() API will probably be universally obtainable.



Source link

This Web site is affiliated with Amazon associates, Clickbank, JVZoo, Sovrn //Commerce, Warrior Plus etc.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *