PushManager: getSubscription() 方法
注意:此功能在Web Workers中可用。
PushManager.getSubscription()
方法是PushManager
接口的方法,用于检索现有的推送订阅。
它返回一个Promise
,该 Promise 解析为一个PushSubscription
对象,其中包含现有订阅的详细信息。如果不存在现有订阅,则解析为 null
值。
语法
js
getSubscription()
参数
无。
返回值
一个Promise
,该 Promise 解析为一个PushSubscription
对象或 null
。
示例
此代码段取自推送消息和通知示例。(没有可用的实时演示。)
js
// We need the service worker registration to check for a subscription
navigator.serviceWorker.ready.then((serviceWorkerRegistration) => {
// Do we already have a push message subscription?
serviceWorkerRegistration.pushManager
.getSubscription()
.then((subscription) => {
// Enable any UI which subscribes / unsubscribes from
// push messages.
const pushButton = document.querySelector(".js-push-button");
pushButton.disabled = false;
if (!subscription) {
// We aren't subscribed to push, so set UI
// to allow the user to enable push
return;
}
// Keep your server in sync with the latest subscriptionId
sendSubscriptionToServer(subscription);
showCurlCommand(subscription);
// Set your UI to show they have subscribed for
// push messages
pushButton.textContent = "Disable Push Messages";
isPushEnabled = true;
})
.catch((err) => {
console.error(`Error during getSubscription(): ${err}`);
});
});
规范
规范 |
---|
Push API # dom-pushmanager-getsubscription |
浏览器兼容性
BCD 表格仅在浏览器中加载