PushManager.getSubscription()

Experimental: 这是一个实验中的功能
此功能某些浏览器尚在开发中,请参考浏览器兼容性表格以得到在不同浏览器中适合使用的前缀。由于该功能对应的标准文档可能被重新修订,所以在未来版本的浏览器中该功能的语法和行为可能随之改变。

PushManager 接口的方法**PushManager.getSubscription()** 尝试获取已有的推送订阅。

它返回一个 Promise 用来 resolve 出一个包含现有订阅的详细信息的PushSubscription (en-US) 对象。如果不存在已有的推送订阅,返回 null。

语法

PushManager.getSubscription().then(function(pushSubscription) { ... } );

参数

无。

返回值

A Promise that resolves to a PushSubscription (en-US) object or null.

例子

这个代码片段来自 push messaging and notification sample. (没有能直接运行的例子.)

// We need the service worker registration to check for a subscription
  navigator.serviceWorker.ready.then(function(serviceWorkerRegistration) {
    // Do we already have a push message subscription?
    serviceWorkerRegistration.pushManager.getSubscription()
      .then(function(subscription) {
        // Enable any UI which subscribes / unsubscribes from
        // push messages.
        var 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(function(err) {
        window.Demo.debug.log('Error during getSubscription()', err);
      });
  });

规范

Specification
Push API
# dom-pushmanager-getsubscription

浏览器兼容性

BCD tables only load in the browser