Creating Scheduled Push Notifications
Timed push notifications: New features of web applications
"Timed" is the key - it's a pretty new feature! When push notifications are scheduled (for example, “The medication time is up” or “You will be boarding in 3 hours”), notifications can be displayed to the user even if they are offline. This improves the limitations that push notifications require users to be online in the past.
So, how does timed notifications work? We will focus on four key parts:
- Register service worker thread
- Add and delete timed push notifications
- Enhance push notifications with action buttons
- Handling push notifications in service worker thread
Background knowledge
Push notifications are a great way to inform website users that important events have occurred and may need to open our (web) application again. With the Notification API (combining the Push API and HTTP Network Push Protocol), the network becomes an easy way to send push notifications from the server to the application and display it on the device.
You may have seen this kind of evolution. For example, how often do you see some kind of prompt to accept notifications from the website? While browser vendors are already struggling to find solutions to reduce this annoyance (both Firefox and Chrome have outlined plans), Chrome 80 is just starting a source code trial of the new notification trigger API, which allows us to create notifications triggered by different events, rather than just server pushes. However, currently, time-based triggers are the only supported events we have. However, other events, such as geolocation-based triggers, are already in the plan.
Scheduling events in JavaScript is very easy, but there is a problem. In our push notification scenario, we cannot determine if the application is running at the exact moment we want to display the notification. This means we can't just schedule at the application layer. Instead, we need to operate at the service worker thread level. This is where the new API comes into play.
The notification trigger API is in the early feedback phase. You need to enable the #enable-experimental-web-platform-features flag in Chrome, or you should register your application for the source code trial.
In addition, the Service Worker Thread API requires a secure connection via HTTPS. So if you try it on your machine, you need to make sure it is served over HTTPS.
set up
I created a very basic setup. We have an application.js file, an index.html file, and a service-worker.js file, and some image resources.
<code>/project-folder ├── index.html ├── application.js ├── service-worker.js └── assets ├─ badge.png └── icon.png</code>
You can find a complete example of the basic notification trigger API demonstration on GitHub.
Register service worker thread
First, we need to register a service worker thread. Currently, it only records the registration success.
// service-worker.js // Listen to the installation event self.addEventListener('install', event => console.log('ServiceWorker installed'));
if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/service-worker.js'); }
Set up push notifications
In our application, we need to request user permissions to display notifications. From there, we will get our service worker thread registration and register a new notification for that scope. So far, nothing new.
The cool part is the new showTrigger property. This allows us to define conditions for displaying notifications. Currently, we want to add a new TimestampTrigger which accepts a timestamp. And since everything happens directly on the device, it works offline as well.
// application.js document.querySelector('#notification-button').onclick = async() => { const reg = await navigator.serviceWorker.getRegistration(); Notification.requestPermission().then(permission => { if (permission !== 'granted') { alert('You need to allow push notifications'); } else { const timestamp = new Date().getTime() 5 * 1000; // Now add 5000 milliseconds reg.showNotification( 'Demo push notification', { tag: timestamp, // Unique ID body: 'Hello, world', // content of push notifications showTrigger: new TimestampTrigger(timestamp), // Set the time of push notifications data: { url: window.location.href, // Pass the current url to notification}, badge: './assets/badge.png', icon: './assets/icon.png', } ); } }); };
Processing notification
Now, notifications should be displayed in the specified timestamp. But now we need a way to interact with it, and that's where we need the service worker thread notificationclick and notificationclose events.
Both events listen for related interactions and both can use the full potential of service worker threads. For example, we can open a new window:
// service-worker.js self.addEventListener('notificationclick', event => { event.waitUntil(self.clients.openWindow('/')); });
This is a very simple example. But with the functionality of service worker threads, we can do more. Let's check if the required window is already open and a new window will only be opened if it is not open.
// service-worker.js self.addEventListener('notificationclick', event => { event.waitUntil(self.clients.matchAll().then(clients => { if (clients.length) { // Check whether at least one tab has clients[0].focus() opened; } else { self.clients.openWindow('/'); } })); });
Notification operation
Another great way to facilitate interaction with users is to add predefined actions to notifications. For example, we can let them choose whether to close notifications or open the app.
// application.js reg.showNotification( 'Demo push notification', { tag: timestamp, // Unique ID body: 'Hello, world', // content of push notifications showTrigger: new TimestampTrigger(timestamp), // Set the time of push notifications data: { url: window.location.href, // Pass the current url to notification}, badge: './assets/badge.png', icon: './assets/icon.png', actions: [ { action: 'open', title: 'Open app' }, { action: 'close', title: 'Close notification', } ] } );
Now we use these notifications in the service worker thread.
// service-worker.js self.addEventListener('notificationclick', event => { if (event.action === 'close') { event.notification.close(); } else { self.clients.openWindow('/'); } });
Cancel push notification
Pending notifications can also be cancelled. In this case, we need to get all pending notifications from the service worker thread and then close them before they are sent to the device.
// application.js document.querySelector('#notification-cancel').onclick = async() => { const reg = await navigator.serviceWorker.getRegistration(); const notifications = await reg.getNotifications({ includeTriggered: true }); notifications.forEach(notification => notification.close()); alert(`${notifications.length} notifications cancelled`); };
Communication
The final step is to set up communication between the application and the service worker thread using the postMessage method on the service worker thread client. Suppose we want to notify that the already activated tab push notification click event has occurred.
// service-worker.js self.addEventListener('notificationclick', event => { event.waitUntil(self.clients.matchAll().then(clients => { if (clients.length) { // Check whether at least one tab has clients[0].focus() opened; clients[0].postMessage('Push notification clicked!'); } else { self.clients.openWindow('/'); } })); });
// application.js navigator.serviceWorker.addEventListener('message', event => console.log(event.data));
Summarize
The Notification API is a very powerful feature that enhances the mobile experience of web applications. It has just received a very important improvement due to the advent of the notification trigger API. The API is still under development, so now is the best time to try it out and give feedback to developers.
If you are using Vue or React, I suggest you check out my own progressive web application demo. It includes a documented example using the notification trigger API of Vue and React, as shown below: (The Vue/React example is omitted here because the original text is not provided)
The above is the detailed content of Creating Scheduled Push Notifications. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



If you’ve recently started working with GraphQL, or reviewed its pros and cons, you’ve no doubt heard things like “GraphQL doesn’t support caching” or

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

No matter what stage you’re at as a developer, the tasks we complete—whether big or small—make a huge impact in our personal and professional growth.

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.
