简体   繁体   中英

firebase web notification - How to use document or window.document in firebase-messaging-sw.js

I have Implemented firebase web notification in my site. I am facing issue in using window.document or document object in service worker firebase-messaging-sw.js.

messaging.setBackgroundMessageHandler(function(payload) {
  // Handle notification when site is in background

  // // Blink title
  var isOldTitle = true;
  var oldTitle = document.title;
  var newTitle =  "(1) New Work Order";
  var interval = null;
  interval = setInterval(function(){
      document.title = isOldTitle ? oldTitle : newTitle;
      isOldTitle = !isOldTitle;
  }, 700);

  // send web browser notification
  var payloadData = JSON.parse(payload.data.notification);
  var notificationOptions = {
    body: payloadData.body,
    icon: payloadData.icon,
    click_action: payloadData.click_action
  };
  return self.registration.showNotification(payloadData.title,notificationOptions);

});

Can anyone suggest me a way to use document object in firebase-messaging-sw.js.

Basically I want achieve is on the notification received I want to change the title of my web site.

Window or document object will not be available inside service worker file. Only way is to communicate to your html or js files. Communication can be send via postmessage api in serviceworker.

self.clients.matchAll().then(clients => {
    clients.forEach(client => {
      client.postmessage(/*data*/);
    });
  });

In your main document, listen for the messages from service worker using:

navigator.serviceWorker.onmessage = (event) => {
  console.log('message from sw');
  /*Here change the document title*/
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM