Home Web Front-end CSS Tutorial Creating Scheduled Push Notifications

Creating Scheduled Push Notifications

Apr 08, 2025 am 09:14 AM

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>
Copy after login

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'));
Copy after login
 if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js');
}
Copy after login

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',
        }
      );
    }
  });
};
Copy after login

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('/'));
});
Copy after login

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('/');
    }
  }));
});
Copy after login

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',
      }
    ]
  }
);
Copy after login

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('/');
  }
});
Copy after login

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`);
};
Copy after login

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('/');
    }
  }));
});
Copy after login
 // application.js
navigator.serviceWorker.addEventListener('message', event => console.log(event.data));
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

While You Weren't Looking, CSS Gradients Got Better While You Weren't Looking, CSS Gradients Got Better Apr 11, 2025 am 09:16 AM

One thing that caught my eye on the list of features for Lea Verou&#039;s conic-gradient() polyfill was the last item:

A Comparison of Static Form Providers A Comparison of Static Form Providers Apr 16, 2025 am 11:20 AM

Let’s attempt to coin a term here: "Static Form Provider." You bring your HTML

See all articles