javascript - firebase web 通知 - 如何在 firebase-messaging-sw.js 中使用 document 或 window.document

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

我已经在我的网站中实现了 firebase web 通知。我在服务 worker 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 中使用文档对象的方法。

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

最佳答案

窗口或文档对象在服务工作线程文件中不可用。唯一的方法是与您的 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*/
}

关于javascript - firebase web 通知 - 如何在 firebase-messaging-sw.js 中使用 document 或 window.document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128347/

相关文章:

java - 计算所有值 Firebase Java API

Azure 通知中心 - 从 GCM 迁移到 FCM

android - Firebase FCM,同一个 firebase 项目中的多个应用程序

javascript - 零作为 IIFE 中的第一个参数

javascript - dojo 中的 return 语句如何工作?

javascript - Angular,$route.current 返回未定义,但 $route 有一个 .current 属性

javascript - jsPDF设置表格样式

java - 将 DataSnapshot 转换为类对象

android - 适用于 Android 的 Firebase Admin SDK,未找到方法

android - startActivity 在 fcm 中的 onMessageReceived 中不起作用