Firebase Web JS,在后台接收通知,然后在您的网页中处理

Firebase Web JS, Receive notification in Background and then process it in your webpage

我正在研究 firebase 云消息传递。

场景: 当我的浏览器处于后台并且我通过 Service Worker 收到通知时,它会在浏览器处理程序中向我显示这样的通知

现在,如果我点击通知或打开浏览器,我将无法在网页中获取该通知的详细信息,

我想要什么

我希望当用户单击通知或打开浏览器时,它应该通过我网页上的 TOASTR JS 等库触发通知,以便用户可以与其交互以转到所需的通知页面或我想要的任何内容在这里做...

服务工作者文件

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

// Initialize Firebase
var firebaseConfig = {
    apiKey: "AIzaSyBvOpTvMo_vxMi1l3EEcd8UbbQPeW2Ktdg",
    authDomain: "educore-portal.firebaseapp.com",
    databaseURL: "https://educore-portal.firebaseio.com",
    projectId: "educore-portal",
    storageBucket: "educore-portal.appspot.com",
    messagingSenderId: "1038865124281",
    appId: "1:1038865124281:web:26a7ae36c7819a170f8468",
    measurementId: "G-N8PGZHM0P5"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();


// If you would like to customize notifications that are received in the
// background (Web app is closed or not in browser focus) then you should
// implement this optional method.
// [START background_handler]
messaging.setBackgroundMessageHandler(function (payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
        body: 'Background Message body.',
        icon: '/firebase-logo.png'
    };

    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});
// [END background_handler]

messaging.onBackgroundMessage((payload) => {
    console.log('Message received.onBackgroundMessage ', payload);
});

FIREBASE 函数初始化

function initFirebase() {
    var firebaseConfig = {
        apiKey: "AIzaSyBvOpTvMo_vxMi1l3EEcd8UbbQPeW2Ktdg",
        authDomain: "educore-portal.firebaseapp.com",
        databaseURL: "https://educore-portal.firebaseio.com",
        projectId: "educore-portal",
        storageBucket: "educore-portal.appspot.com",
        messagingSenderId: "1038865124281",
        appId: "1:1038865124281:web:26a7ae36c7819a170f8468",
        measurementId: "G-N8PGZHM0P5"
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
    const messaging = firebase.messaging();
    messaging.usePublicVapidKey("BJ3u-j-0W2m1it06nryDvW8dV9X7uzl6i9la_lyEKPLYkmZHVxqGpCwF8l-vXCHx6sAcOa3O2WGnVdAsVbA2-Rc");
    // Get Instance ID token. Initially this makes a network call, once retrieved
    // subsequent calls to getToken will return from cache.
    messaging.getToken().then((currentToken) => {
        if (currentToken) {
            console.log('currentToken', currentToken);
        } else {
            // Show permission request.
            console.log('No Instance ID token available. Request permission to generate one.');
        }
    }).catch((err) => {
        console.log('An error occurred while retrieving token. ', err);
    });


    // Handle incoming messages. Called when:
    // - a message is received while the app has focus
    // - the user clicks on an app notification created by a service worker
    //   `messaging.setBackgroundMessageHandler` handler.
    messaging.onMessage((payload) => {
        console.log('Message received. ', payload);
        toastr["info"](payload.notification.body, payload.notification.title);
        // ...
    });

}

我试图寻找一种方法来在浏览器处于后台时在收到通知时在我的网页内触发通知。但是我没有找到任何与 Firebase 相关的解决方案。

所以我想到的是利用 文档可见性更改事件侦听器

这是如何使用它的基本结构。 每次更改选项卡的可见性状态时都会调用它。 因此,每当用户返回我的网页时,我都会调用函数来检查新消息(如果找到),然后触发其他函数来显示通知或刷新聊天消息等....

希望对大家有所帮助...

document.addEventListener("visibilitychange", function() {
  console.log( document.visibilityState );
  //Run code snippet and switch the tab/browser and come back again
  //hidden
  //visible
});