Push API
Push API (推送API)
Push API: Enabling Real-Time Notifications in Web Applications
Push API: Enabling Real-Time Notifications in Web Applications
The Push API is a web technology that enables web developers to deliver real-time notifications and updates to users’ devices, even when the web application is not actively open in a browser tab. It allows websites to send push messages to a user’s browser, making it a powerful tool for engaging users and keeping them informed. In this article, we’ll explore what the Push API is, its benefits, how it works, and some common use cases. (Push API是一种Web技术,使Web开发人员能够向用户的设备提供实时通知和更新,即使Web应用程序未在浏览器选项卡中主动打开。它允许网站向用户的浏览器发送推送消息,使其成为吸引用户并让他们随时了解情况的强大工具。在本文中,我们将探讨什么是Push API ,它的好处,它是如何工作的,以及一些常见的用例。)
What is the Push API?
The Push API is a JavaScript API that enables web applications to receive push messages from remote servers or services. These messages can trigger notifications, updates, or other actions in the user’s web browser, even if the website is not currently open. Push messages are typically short and can include text, images, or links. (推送API是一种JavaScript API ,使Web应用程序能够从远程服务器或服务接收推送消息。即使网站当前未打开,这些消息也可能在用户的网络浏览器中触发通知、更新或其他操作。推送消息通常很短,可以包含文本、图片或链接。)
Benefits of the Push API
Real-Time Notifications The Push API allows web applications to deliver real-time notifications to users, enhancing user engagement and keeping them informed.
Engagement and Retention Push notifications can help retain users by reminding them of your website’s presence and encouraging them to return.
Cross-Platform Support Push notifications work across various devices and platforms, including desktop and mobile browsers.
(实时通知 Push API允许Web应用程序向用户提供实时通知,增强用户参与度并让他们随时了解情况。
参与度和留存率 推送通知可以通过提醒用户您的网站存在并鼓励他们返回来帮助留住用户。
跨平台支持 推送通知适用于各种设备和平台,包括桌面和移动浏览器。) Opt-In Model Users must grant explicit permission to receive push notifications, ensuring that they have control over their notification preferences.
Background Sync Push messages can trigger background processes and updates, allowing web apps to stay up-to-date even when not in active use. (Opt-In模型 用户必须授予接收推送通知的明确权限,确保他们可以控制其通知首选项。
后台同步 推送消息可以触发后台进程和更新,从而使Web应用即使在不活动使用时也能保持最新状态。)
How Push API Works
The Push API operates through a series of steps:
User Permission: Before a website can send push notifications, the user must grant explicit permission. This permission is requested when the user visits the website and clicks on a prompt requesting push notification access.
Service Worker: The website sets up a service worker, a script that runs in the background, listening for incoming push messages. The service worker is registered with the browser when the user grants permission.
Push Subscription: After the service worker is registered, the website obtains a push subscription from the browser. This subscription includes a unique endpoint URL and an encryption key pair.
Server Integration: The website’s server stores the push subscription details and can use them to send push messages to the user’s browser.
Push Message: When the server wants to send a push notification, it uses the push subscription endpoint and encryption key to send a push message to the user’s browser.
Service Worker Activation: The user’s browser activates the service worker when it receives a push message, even if the website is not open in a tab.
Notification Display: The service worker can then display a notification to the user’s device based on the contents of the push message.
Common Use Cases for Push API
News and Updates: Websites can send push notifications to users when new articles, updates, or important news items are available.
Social Media: Social media platforms use push notifications to alert users about new messages, likes, comments, or friend requests.
E-commerce: E-commerce websites can notify users about special offers, promotions, or product availability.
Reminders and Alerts: Web apps can send reminders and alerts for events, appointments, or tasks.
Real-Time Updates: Apps that provide real-time data, such as sports scores, stock prices, or weather updates, can use push notifications to keep users informed.
Basic Example: Sending a Push Notification
Here’s a simplified example of how a web server can send a push notification to a user’s browser using the Push API:
// On the server-side
const pushSubscription = getPushSubscriptionFromDatabase(userId); // Retrieve user's push subscription
const pushMessage = {
title: 'New Message',
body: 'You have a new message from a friend.',
icon: 'notification-icon.png',
};
sendPushNotification(pushSubscription, pushMessage); // Send push notification to the user
// In the service worker
self.addEventListener('push', event => {
const options = {
body: event.data.text(),
icon: 'notification-icon.png',
};
event.waitUntil(self.registration.showNotification('New Message', options));
});
In this example:
The server retrieves the user’s push subscription and sends a push message. (-服务器检索用户的推送订阅并发送推送消息。)
The service worker listens for incoming push messages and displays a notification when one is received. (- Service Worker监听传入的推送消息,并在收到推送消息时显示通知。)
Implementing the Push API
To enable your web application to receive push messages, you need to have an active service worker. When the service worker is active, it can subscribe to push notifications using the &aposPushManager.subscribe()&apos method. (若要使Web应用程序能够接收推送消息,您需要有一个活动的Service Worker。当Service Worker处于活动状态时,它可以使用& aposPushManager.subscribe () & apos方法订阅推送通知。)
// In your service worker script
self.addEventListener('push', event => {
// Handle incoming push messages here
(//在此处处理传入的推送消息)
const pushMessage = event.data.text();
// Display a notification or perform custom actions
});
The resulting &aposPushSubscription&apos includes all the information needed to send a push message to the application. This information includes an endpoint URL and an encryption key required for sending data securely. (生成的& aposPushSubscription&apos包含向应用程序发送推送消息所需的所有信息。此信息包括安全发送数据所需的端点URL和加密密钥。)
// In your web application code
navigator.serviceWorker.ready.then(registration => {
registration.pushManager.subscribe({ userVisibleOnly: true })
.then(subscription => {
// Subscription object contains endpoint and keys
(//Subscription对象包含端点和键)
const endpoint = subscription.endpoint;
const publicKey = subscription.options.applicationServerKey;
// Send this information to your server for message sending
(//将此信息发送到服务器进行消息发送)
})
.catch(error => {
console.error('Error subscribing to push:', error);
});
});
Handling Incoming Push Messages (处理传入的推送消息)
The service worker is automatically started when needed to handle incoming push messages. These messages are delivered to the &apospush&apos event handler in your service worker script. (当需要处理传入的推送消息时, Service Worker会自动启动。这些消息将传递到Service Worker脚本中的& apospush&apos事件处理程序。)
// In your service worker script
self.addEventListener('push', event => {
// Handle incoming push messages here
(//在此处处理传入的推送消息)
const pushMessage = event.data.text();
// Display a notification or perform custom actions
});
Typically, you would use this event handler to display a notification to the user. You can customize the notification’s content and appearance using the &aposServiceWorkerRegistration.showNotification()&apos method. (通常,您将使用此事件处理程序向用户显示通知。您可以使用& aposServiceWorkerRegistration.showNotification () & APOS方法自定义通知的内容和外观。)
// In your service worker script
self.addEventListener('push', event => {
const pushMessage = event.data.text();
event.waitUntil(
(event.waitUntil ()
self.registration.showNotification('New Message', {
body: pushMessage,
icon: 'notification-icon.png',
})
);
});
Security Considerations (安全考虑)
Each subscription is unique to a service worker, and the endpoint URL is a unique capability URL. Knowledge of the endpoint URL is all that is necessary to send a message to your application. Therefore, it’s crucial to keep the endpoint URL secret to prevent other applications from sending push messages to your application. (每个订阅对Service Worker都是唯一的,端点URL是唯一的功能URL。了解端点URL是向应用程序发送消息所必需的。因此,将端点URL保密至关重要,以防止其他应用程序向您的应用程序发送推送消息。)
Resource Usage and Browser-Specific Behavior (资源使用和浏览器特定行为)
Activating a service worker to deliver a push message can result in increased resource usage, particularly of the battery. Different browsers have different mechanisms for handling this, and there is currently no standard mechanism. (激活Service Worker以传递推送消息可能会导致资源使用量增加,尤其是电池的使用量。不同的浏览器有不同的机制来处理这个问题,目前还没有标准的机制。)
Firefox allows a limited number (quota) of push messages to be sent to an application, but push messages that generate notifications are exempt from this limit. The limit is refreshed each time the site is visited. (- Firefox允许向应用程序发送有限数量(配额)的推送消息,但生成通知的推送消息不受此限制。每次访问网站时都会刷新限制。)
In Chrome, there are no specific limits for push messages. (-在Chrome浏览器中,推送消息没有特定限制。)
These browser-specific considerations are important to keep in mind when developing and testing your push notification system. (在开发和测试推送通知系统时,请务必记住这些特定于浏览器的注意事项。)
By following these implementation guidelines and considering security and resource usage, you can effectively harness the power of the Push API to deliver real-time notifications and updates to your web application’s users, enhancing their experience and engagement. (通过遵循这些实施指南并考虑安全性和资源使用情况,您可以有效地利用Push API的强大功能向Web应用程序的用户提供实时通知和更新,从而增强他们的体验和参与度。)
Interfaces
PushEvent The &aposPushEvent&apos interface represents a push action that is sent to the global scope of a ServiceWorker. It contains information sent from an application to a &aposPushSubscription&apos. This interface is crucial for handling incoming push messages within a service worker.
PushManager The &aposPushManager&apos interface provides a way to receive notifications from third-party servers and request URLs for push notifications. It allows you to manage push subscriptions, subscribe to push notifications, check the status of push permissions, and perform other operations related to push messaging. PushMessageData The &aposPushMessageData&apos interface provides access to push data sent by a server. It includes methods to manipulate the received data, making it possible to process and handle push messages efficiently within a service worker. PushSubscription The &aposPushSubscription&apos interface represents a subscription’s URL endpoint, which is necessary for sending push messages to the subscribed user. It also allows users to unsubscribe from a push service, providing control over their push notification preferences. PushSubscriptionOptions The &aposPushSubscriptionOptions&apos interface represents the options associated with a push subscription. These options can include settings such as the expiration time of a subscription or additional metadata related to the subscription.
Service Worker Additions
ServiceWorkerRegistration.pushManager (Read-only) The &aposServiceWorkerRegistration.pushManager&apos property returns a reference to the &aposPushManager&apos interface for managing push subscriptions. It serves as the entry point for using Push messaging within a service worker. Developers can use this property to subscribe to push notifications, retrieve active subscriptions, and check the permission status for push messaging. onpush Event Handler The &aposonpush&apos event handler is fired whenever a push event occurs. This event handler is essential for responding to server push messages received by the service worker. It allows developers to define actions to be taken when a push notification is received, such as displaying a notification to the user or processing the message data. onpushsubscriptionchange Event Handler The &aposonpushsubscriptionchange&apos event handler is fired whenever a &apospushsubscriptionchange&apos event occurs. This event is triggered when a push subscription is invalidated or is about to be invalidated, such as when a push service sets an expiration time. Developers can use this event handler to handle changes in push subscriptions and perform necessary updates or cleanup operations. These interfaces and Service Worker additions are essential components of the Push API, enabling web developers to implement real-time push notifications and efficiently manage push messaging within web applications. Conclusion The Push API is a powerful tool for web developers to engage users and deliver real-time notifications and updates. By using this technology, web applications can enhance user experience, increase user retention, and keep users informed about important events and updates, all while respecting user privacy and consent. Whether you’re building a news website, a messaging app, or any web application that requires real-time communication, the Push API provides the means to deliver timely and relevant information to your users.