【问题标题】:How to use pusher.js in service worker如何在服务工作者中使用 pusher.js
【发布时间】:2022-07-11 14:23:22
【问题描述】:

我想在服务工作者中使用 pusher.js 在应用程序(pwa)关闭时向用户发送通知。但我在 pusher.js 中遇到以下错误:

window is not defined

【问题讨论】:

    标签: progressive-web-apps service-worker pusher-js


    【解决方案1】:

    我得到了答案,在 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';
    

    【讨论】:

    • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    根据 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/

    【讨论】:

      猜你喜欢
      • 2020-08-12
      • 2017-11-22
      • 1970-01-01
      • 2019-07-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-02
      • 1970-01-01
      相关资源
      最近更新 更多