getSubscription returns a null subscription

夙愿已清 提交于 2019-12-01 07:18:57

Initially, when the user isn't subscribed, the promise returned by getSubscription resolves to null. You need to call registration.pushManager.subscribe in order to subscribe the user (and then, the next time the user visits your site, getSubscription will resolve with a non-null subscription).

There are many examples on the ServiceWorker Cookbook.

A simple example here:

// Use the PushManager to get the user's subscription to the push service.
serviceWorkerRegistration.pushManager.getSubscription()
.then(function(subscription) {
  // If a subscription was found, return it.
  if (subscription) {
    return subscription;
  }

  // Otherwise, subscribe the user (userVisibleOnly allows to specify
  // that we don't plan to send notifications that don't have a
  // visible effect for the user).
  return serviceWorkerRegistration.pushManager.subscribe({
    userVisibleOnly: true
  });
})
.then(function(subscription) {
  // Here you can use the subscription.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!