`pushManager.subscribe` 和 `pushManager.getSubscription` Service Worker 的区别是什么

What are the difference between `pushManager.subscribe` and `pushManager.getSubscription` Service Worker's

PushManager.getSubscription()

Retrieves an existing push subscription. It returns a Promise that resolves to a PushSubscription object containing details of an existing subscription. If no existing subscription exists, this resolves to a null value.

[...]

PushManager.subscribe()

Subscribes to a push service. It returns a Promise that resolves to a PushSubscription object containing details of a push subscription. A new push subscription is created if the current service worker does not have an existing subscription.

根据 MDN 的 pushManager 文档。这些方法几乎相同,除了在 getSubcription() 的情况下它可能会用空值解析。

我基本上明白我可以简单地使用 subscribe() 并且 Service Worker 将尝试在可用的情况下获取订阅,并在不可用的情况下创建新的订阅。

=> 但我正在尝试做其他事情。我想先尝试获得订阅,如果它通过 null 解决,我会尝试订阅它。

    navigator.serviceWorker.register('./worker.js')
    .then(function(reg) {

        // Subscribe push manager
        reg.pushManager.getSubscription()
        .then(function(subscription) {

            if(subscription){
                // TODO... get the enpoint here
            } else {
                reg.pushManager.subscribe()
                .then(function(sub){
                    // TODO... get the endpoint here
                });
            }

        }, function(error) {
            console.error(error);
        })
    });

但后来我遇到了错误:

Uncaught (in promise) DOMException: Subscription failed - no active Service Worker

令人困惑,我怀疑这是 Chrome 对 Service Worker 的 Push API 的限制,或者可能是一个错误。有人知道关于这种奇怪行为的任何信息吗?

问题是您的 Service Worker 已注册,但尚未激活。

您可以使用 navigator.serviceWorker.ready 而不是在注册 Service Worker 后立即订阅。

如果想让service worker尽快激活,可以使用skipWaiting and Clients.claim, as described in this ServiceWorker Cookbook recipe.