及时向用户发送实用通知。
2016 年,W3C 的 Web 应用工作组发布了 Push API 和 Notification API,推送通知也随之标准化。这些 API 为 Web 开发者提供了将推送通知纳入其 Web 应用的必要功能,并为用户提供了在 Web 浏览器上接收通知并与之互动的必要功能。推送消息是指网站或应用向用户网络浏览器发送的通知,前提是用户之前已向该网站或应用授予发送通知的权限。这些消息可用于提醒用户有新内容或更新,提醒用户有即将到来的活动或截止日期,或提供其他重要信息。推送消息对于需要向用户及时传递相关信息的应用(例如新闻应用或体育应用)或希望向用户发送有关特惠或促销活动通知的电子商务网站特别有用。
如需订阅推送通知,请先检查浏览器是否支持推送通知,方法是检查 navigator 和 window 对象中是否存在 serviceWorker 和 PushManager 对象。
如果支持推送通知,请使用 async 和 await 关键字注册服务工作线程并订阅推送通知。以下示例展示了如何使用 JavaScript 执行此操作:
// Check if the browser supports push notifications.
if ("serviceWorker" in navigator && "PushManager" in window) {
try {
// Register the service worker.
const swReg = await navigator.serviceWorker.register("/sw.js");
// Subscribe for push notifications.
const pushSubscription = await swReg.pushManager.subscribe({
userVisibleOnly: true
});
// Save the push subscription to the database.
savePushSubscription(pushSubscription);
} catch (error) {
// Handle errors.
console.error("Error subscribing for push notifications.", error);
}
} else {
// Push notifications are not supported by the browser.
console.error("Push notifications are not supported by the browser.");
}