【问题标题】:What is the use of firebase-messaging-sw.js in firebase web notifications?firebase 网络通知中 firebase-messaging-sw.js 的用途是什么?
【发布时间】:2017-07-16 06:57:44
【问题描述】:

我已在我的网站上为 firebase 推送通知配置了 Javascript API。一切正常,但我看到许多“背景消息”。我刚刚将 firebase-messaging-sw.js 文件放在了我网站的目录中。

我不知道它的用途。我只是想知道它的作用。如果您看到以下代码,您会看到我没有提供 messagingSenderId 仍然执行此文件。

所以我想知道的是:

没有 ID 怎么办?

它有什么用?接收推送通知并在onMessage处理程序中处理它们是强制性文件吗?

我应该把这个文件放在哪里(我的当前目录是:MY-SITE-DOMAIN/firebase-messaging-sw.js,但firebase通知配置在不同的目录中)?

代码如下:

importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.5.2/firebase-messaging.js');

firebase.initializeApp({
  'messagingSenderId': 'YOUR-SENDER-ID'
});

const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
 console.log('[firebase-messaging-sw.js] Received background message ', payload);
 const notificationTitle = 'Background Message from html';
  const notificationOptions = {
   body: 'Background Message body.',
   icon: '/firebase-logo.png'
 };

  return self.registration.showNotification(notificationTitle,
     notificationOptions);
});

原始文件为here

【问题讨论】:

  • importscripts 在我的应用程序中不起作用,为什么:(

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


【解决方案1】:

您可以使用下面的配置,也可以只使用messagingSenderID。 您可能已经在其他 javascript 中设置了配置,因此它没有引发任何错误。

var config = {
        apiKey: "",
        authDomain: "",
        databaseURL: "",
        storageBucket: "",
        messagingSenderId: ""
    };

firebase-messaging-sw.js 是必须的并且应该存在于主机根目录中。当浏览器不在焦点或后台时,这是设置后台通知处理程序所必需的。

【讨论】:

  • 有没有链接/来源可以确认firebase-messaging-sw.js should be present in the host root directory
  • @NimitBhargava:给你:firebase.google.com/docs/cloud-messaging/js/… - 第二段create an empty file with that name and place it in the root of your domain before retrieving a token
【解决方案2】:

默认情况下,firebase 将寻找 /firebase-messaging-sw.js,其中应包含 firebase 库和侦听器。更多细节在这里:https://firebase.google.com/docs/cloud-messaging/js/receive

如果您想使用现有的 Service Worker,可以使用 https://firebase.google.com/docs/reference/js/firebase.messaging.Messaging#useServiceWorker

像这样……

navigator.serviceWorker.register('/service-worker.js').then(registration => {
  firebase.messaging().useServiceWorker(registration)
})

【讨论】:

    【解决方案3】:

    在项目根目录创建空文件firebase-messaging-sw.js

    【讨论】:

      【解决方案4】:

      在 Apache Tomcat 中,在 /usr/share/apache-tomcat-9.0.30/webapps/ROOT 创建

      【讨论】:

        猜你喜欢
        • 2020-01-27
        • 1970-01-01
        • 1970-01-01
        • 2021-01-15
        • 1970-01-01
        • 2017-03-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多