簡體   English   中英

firebase-messaging-sw.js 在 firebase web 通知中有什么用?

[英]What is the use of firebase-messaging-sw.js in firebase web notifications?

我已經在我的網站上為 firebase 推送通知配置了 Javascript API。 一切正常,但我看到很多“背景消息”。 我剛剛將firebase-messaging-sw.js文件放在我網站的目錄中。

我不知道它的用途。 我只是想知道它的作用。 如果您看到以下代碼,您會看到我還沒有提供messagingSenderId仍然執行此文件。

所以我想知道的是:

沒有身份證怎么辦?

它有什么用? 接收推送通知並在onMessage處理程序中處理它們是否是強制性文件?

我應該把這個文件放在哪里(我當前的目錄是: MY-SITE-DOMAIN/firebase-messaging-sw.jsfirebase通知配置在不同的目錄中)?

這是代碼:

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

原始文件在這里

默認情況下,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)
})

您可以使用以下配置或僅使用 messagesSenderID。 您可能已經在其他 javascript 中設置了配置,因此它沒有拋出任何錯誤。

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

firebase-messaging-sw.js 是必須的,並且應該存在於主機根目錄中。 當瀏覽器不在焦點或在后台時,這是設置后台通知處理程序所必需的。

在項目根目錄創建空文件firebase-messaging-sw.js

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM