【问题标题】:firebase web notification - How to use document or window.document in firebase-messaging-sw.jsfirebase web 通知 - 如何在 firebase-messaging-sw.js 中使用 document 或 window.document
【发布时间】:2020-01-27 09:56:18
【问题描述】:

我已在我的网站中实施了 firebase 网络通知。我在服务工作者 firebase-messaging-sw.js 中使用 window.document 或文档对象时遇到问题。

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

});

谁能给我建议一种在 firebase-messaging-sw.js 中使用文档对象的方法。

基本上我想要实现的是收到通知我想更改我的网站的标题。

【问题讨论】:

    标签: javascript firebase firebase-cloud-messaging service-worker


    【解决方案1】:

    窗口或文档对象在 service worker 文件中不可用。唯一的方法是与您的 html 或 js 文件进行通信。可以通过 serviceworker 中的 postmessage api 发送通信。

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

    在您的主文档中,使用以下命令监听来自 service worker 的消息:

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

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-12-13
      • 2022-11-22
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2017-03-29
      相关资源
      最近更新 更多