ServiceWorkerGlobalScope: pushsubscriptionchange event - Web APIs 编辑

The pushsubscriptionchange event is sent to the global scope of a ServiceWorker to indicate a change in push subscription that was triggered outside the application's control. This may occur if the subscription was refreshed by the browser, but it may also happen if the subscription has been revoked or lost.

BubblesNo
CancelableNo
InterfacePushSubscriptionChangeEvent
Event handler propertyonpushsubscriptionchange

Usage notes

Although examples demonstrating how to share subscription related information with the application server tend to use fetch(), this is not necessarily the best choice for real-world use, since it will not work if the app is offline, for example.

Consider using another method to synchronize subscription information between your service worker and the app server, or make sure your code using fetch() is robust enough to handle cases where attempts to exchange data fail.

Note: In earlier drafts of the specification, this event was defined to be sent when a PushSubscription has expired.

Examples

This example, run in the context of a service worker, listens for a pushsubscriptionchange event and re-subscribes to the lapsed subscription.

self.addEventListener("pushsubscriptionchange", event => {
  event.waitUntil(swRegistration.pushManager.subscribe(event.oldSubscription.options)
    .then(subscription => {
      return fetch("register", {
        method: "post",
        headers: {
          "Content-type": "application/json"
        },
        body: JSON.stringify({
          endpoint: subscription.endpoint
        })
      });
    })
  );
}, false);

When a pushsubscriptionchange event arrives, indicating that the subscription has expired, we resubscribe by calling the push manager's subscribe() method. When the returned promise is resolved, we receive the new subscription. This is delivered to the app server using a fetch() call to post a JSON formatted rendition of the subscription's endpoint to the app server.

You can also use the onpushsubscriptionchange event handler property to set up the event handler:

self.onpushsubscriptionchange = event => {
  event.waitUntil(swRegistration.pushManager.subscribe(event.oldSubscription.options)
    .then(subscription => {
      /* ... */
    )
};

Specifications

SpecificationStatusComment
Push API
The definition of 'pushsubscriptionchange' in that specification.
Working DraftInitial specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:104 次

字数:5077

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文