skip to Main Content

I am receiving data in my public folder file, which is firebase-messaging-sw.js from source code e.g main thread with postMessage method. I want to use that data received into messaging.onBackgroundMessage function. Here is my code:

self.addEventListener("message", event => {
  const messageData = event.data
  console.log(messageData)
})
messaging.onBackgroundMessage((payload) => {
  // const notification = new Notification(messageData[keywords][lang]![title], {
  //   body: messageData[keywords][lang]![body]
  // });
  storeMessage(payload.data);
});

I want to use that messageData into messaging.onBackgroundMessage function. I have tried declaring let messageData outside of function scopes but it doesn’t work.

2

Answers


  1. you can return the value of variable.

    Login or Signup to reply.
  2. In the code snippet below, messageData is available in messaging.bar

    So either your messageData variable isn’t accessible, or the second event handler (onBackgroundMessage) is occurring before the first (message event)

    let self = {}, messaging = {}, messageData;
    
    self.foo = (event => {
      messageData = event.data
      console.log(messageData)
    })
    messaging.bar = ((payload) => {
      // const notification = new Notification(messageData[keywords][lang]![title], {
      //   body: messageData[keywords][lang]![body]
      // });
    //  storeMessage(payload.data);
      console.log(messageData);
    });
    
    var event = {};
    event.data = "test";
    self.foo(event);
    messaging.bar();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search