如何为现有 Web 推送订阅者更新我的 Service Worker?

问题描述 投票:0回答:1

我有一个简单的 Web 应用程序,可与 Web 推送和通知 API 配合使用,我使用 FCM 发送消息,并使用 JS 中的一个简单的 Service Worker 来显示浏览器收到的通知。

我的问题是,当我更新 Service Worker 文件时,更改没有反映出来(我添加了对图像 + 图标的支持,之前我在推送通知中仅显示图标)。

我读到 Service Worker 要么在 24 小时内自动更新,要么在使用它的最后一个页面关闭时更新? (这是针对所有订户/用户还是仅针对这 1 个特定订户/用户?

现在已经超过 24 小时了,我看不到任何变化。

我现在有大约 1k 订阅者,似乎仍然没有向他们显示图标+图像,我如何“强制”他们更新 Service Worker?这是否可以远程进行,或者他们需要再次访问我的网站?

我阅读了有关 .update() 和 .skipWaiting() 方法的信息,尽管我不确定如何应用它们,特别是当我需要对现有订阅者进行这些更改时。

这里的示例是我当前的 firebase-messaging-sw.js:

self.addEventListener("push", (event) => {
    const notif = event.data.json().notification;
    event.waitUntil(self.registration.showNotification(notif.title, {
        body: notif.body,
        icon: notif.data.icon,
        image: notif.image,
        data: {
            url: notif.click_action
        }
    }));
});

self.addEventListener("notificationclick", (event) => {
    const clickedNotification = event.notification;
    clickedNotification.close();
    event.WaitUntil(clients.openWindow(event.notification.data.url));
});
javascript push-notification firebase-cloud-messaging service-worker
1个回答
0
投票

在安装事件中,您可以强制等待的 Service Worker 成为活动的 Service Worker。

self.addEventListener('install', event => {
  self.skipWaiting();
});

并且在激活事件中,您可以告诉活动的 Service Worker 立即控制页面。

self.addEventListener('activate', event => {
  self.clients.claim();
});
© www.soinside.com 2019 - 2024. All rights reserved.