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!

If you've ever had to display an interactive animation during a live talk or a class, then you may know that it's not always easy to interact with your slides

With Astro, we can generate most of our site during our build, but have a small bit of server-side code that can handle search functionality using something like Fuse.js. In this demo, we’ll use Fuse to search through a set of personal “bookmarks” th

I wanted to implement a notification message in one of my projects, similar to what you’d see in Google Docs while a document is saving. In other words, a

Some months ago I was on Hacker News (as one does) and I ran across a (now deleted) article about not using if statements. If you’re new to this idea (like I

Since the early days of science fiction, we have fantasized about machines that talk to us. Today it is commonplace. Even so, the technology for making

I remember when Gutenberg was released into core, because I was at WordCamp US that day. A number of months have gone by now, so I imagine more and more of us

The idea behind most of web applications is to fetch data from the database and present it to the user in the best possible way. When we deal with data there

Let's do a little step-by-step of a situation where you can't quite do what seems to make sense, but you can still get it done with CSS trickery. In this


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function