Search code examples
javascriptevent-handlingservice-worker

How to move variable out of local scope in service-worker


I am sending data with Broadcast Channel API from source code to service-worker: firebase-messaging-sw.js. Then I retrieve it in service-worker with the following function: const mainChannel = new BroadcastChannel("main-channel"); mainChannel.onmessage = (data) => {console.log(data)}

Question is that how can I use data retireved from mainChannel.onmessage function to use it in another function?

I have tried to declare global variable and then assign data to it and then use it inside another function but it doesn't work and I can't figure out why. Here is what I tried.

let translateData = {}
const mainChannel = new BroadcastChannel("main-channel");
mainChannel.onmessage = (data) => {
  translateData = data;
}

self.addEventListener('push', (event) => {
  messaging.onBackgroundMessage(function (payload) {
    console.log(translateData)
    storeMessage(payload.data);
    const notificationTitle = payload.data.title;
    const notificationOptions = { body: payload.data.body };
    return event.waitUntil(self.registration.showNotification(notificationTitle, notificationOptions));
  });
});````

Solution

  • The problem was that it was asynchronous. I solved this problem by using Promise. Here is the code:

    let data = {};
    
    const mainChannel = new BroadcastChannel("main-channel");
    const onDataUpdate = new Promise((resolve) => {
      mainChannel.onmessage = (translateData) => {
        data = translateData?.data;
        resolve(data); // Resolve the Promise with the updated data
      };
    });
    

    With this implementation, I could use data in onBackgroundMessage function.