【发布时间】:2022-07-11 14:23:22
【问题描述】:
我想在服务工作者中使用 pusher.js 在应用程序(pwa)关闭时向用户发送通知。但我在 pusher.js 中遇到以下错误:
window is not defined
【问题讨论】:
标签: progressive-web-apps service-worker pusher-js
我想在服务工作者中使用 pusher.js 在应用程序(pwa)关闭时向用户发送通知。但我在 pusher.js 中遇到以下错误:
window is not defined
【问题讨论】:
标签: progressive-web-apps service-worker pusher-js
我得到了答案,在 service worker 中你不能像下面这样导入 pusher:
import Pusher from 'pusher-js';
改为如下导入:
importScripts("https://js.pusher.com/7.0/pusher.worker.min.js");
或者
import Pusher from 'pusher-js/worker';
【讨论】:
根据 Pusher 文档,导入脚本的正确方法是:
importScripts("https://js.pusher.com/beams/service-worker.js");
// The rest of your Service Worker code goes here...
不确定您要达到什么目的,但在我的情况下,我需要操纵新通知以显示不同的消息,我使用:
importScripts("https://js.pusher.com/beams/service-worker.js");
PusherPushNotifications.onNotificationReceived = ({ pushEvent, payload }) => {
// NOTE: Overriding this method will disable the default notification
// handling logic offered by Pusher Beams. You MUST display a notification
// in this callback unless your site is currently in focus
// https://developers.google.com/web/fundamentals/push-notifications/subscribing-a-user#uservisibleonly_options
// Your custom notification handling logic here ?️
// https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration/showNotification
pushEvent.waitUntil(
self.registration.showNotification(payload.notification.title, {
body: payload.notification.body,
icon: payload.notification.icon,
data: payload.data,
})
);
};
来源:https://pusher.com/docs/beams/guides/handle-incoming-notifications/web/
【讨论】: