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
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
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';
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/