0

I want to use pusher.js in service worker for sending notification to user when the app(pwa) is closed. But I get below error in pusher.js:

window is not defined

2 Answers2

3

I got the answer, in service worker you can not import pusher as below:

import Pusher from 'pusher-js';

Instead import as below:

importScripts("https://js.pusher.com/7.0/pusher.worker.min.js");

Or

import Pusher from 'pusher-js/worker';
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 09 '22 at 09:26
0

According with Pusher docs the correct way to import the script is:

importScripts("https://js.pusher.com/beams/service-worker.js");
// The rest of your Service Worker code goes here...

Not sure what are you trying to achieve but in my case I needed to manipulate the new notifications to display different messages, and I made it using:

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,
    })
  );
};

Source: https://pusher.com/docs/beams/guides/handle-incoming-notifications/web/

Diego Borigen
  • 545
  • 4
  • 6