借助浏览器发送系统通知

Web 通知是一个强大的工具,能让网站在用户的设备上显示消息,即使用户当前并未浏览网站。这为用户交互提供了新的可能性,可以用来通知新消息、更新或警告等。本文将指导你如何使用 Web Push API 和 Service Workers 在浏览器中发送系统通知。

订阅推送服务

要使用 Web Push API,首先需要获取用户的许可并订阅推送服务。以下是在前端使用 JavaScript(或 TypeScript)完成这个步骤的代码:

javascript
1navigator.serviceWorker.ready
2  .then((serviceWorkerRegistration) => {
3    const subscribeOptions = {
4      userVisibleOnly: true,
5      applicationServerKey: '使用 nodejs web-push 库生成'
6    };
7
8    return serviceWorkerRegistration.pushManager.subscribe(subscribeOptions);
9  })
10  .then((pushSubscription) => {
11    console.log('Received PushSubscription: ', JSON.stringify(pushSubscription));
12    sendSubscriptionToServer(pushSubscription);
13  });

这段代码首先确保 Service Worker 已经准备就绪,然后通过 pushManager.subscribe 方法创建一个订阅。注意,这会弹出一个提示让用户允许或拒绝通知。

服务器端发送通知

我们将在服务器端使用 Node.js 的 web-push 库发送通知。首先,我们需要设置我们的 VAPID keys:

javascript
1const webpush = require('web-push');
2
3const vapidKeys = {
4  publicKey: 'Your public key',
5  privateKey: 'Your private key'
6};
7
8webpush.setVapidDetails(
9  'mailto:[email protected]',
10  vapidKeys.publicKey,
11  vapidKeys.privateKey
12);

然后,我们可以使用订阅的信息来发送通知:

javascript
1const subscription = {
2  endpoint: 'Endpoint from subscription',
3  keys: {
4    p256dh: 'p256dh key from subscription',
5    auth: 'auth key from subscription'
6  }
7};
8
9const pushPayload = {
10  title: 'Your notification title',
11  message: 'Your notification message'
12};
13
14webpush.sendNotification(subscription, JSON.stringify(pushPayload))
15  .catch((err) => {
16    console.error(err);
17  });

Demo

https://github.com/powerfulyang/powerfulyang.com/blob/master/src/hooks/useNotification.ts

https://github.com/powerfulyang/api.powerfulyang.com/blob/master/src/web-push/web-push.service.e2e.spec.ts