首页 > 解决方案 > 点击推送通知不会每次都打开新的网址

问题描述

我想每次点击 javascript 中的通知时打开一个新 URL。使用以下代码,我可以接收推送通知。我可以重定向到我第一次发送的 URL。但是第二次我无法重定向到新的 URL,而是重定向到我之前传递的 URL。这是我的代码,请帮助我。

const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
    console.log('[firebase-messaging-sw.js] Received background message', payload.data);
    const notification = payload.data;
    const notificationTitle = notification.title;
    const notificationOptions = {
        body: notification.message,
        icon: notification.icon || "/images/icon.png"
    };
    self.addEventListener('notificationclick', function(event) {
        event.notification.close();
        event.waitUntil(self.clients.openWindow(notification.url));
    });
    return self.registration.showNotification(notificationTitle, notificationOptions);
});

标签: javascriptnode.jsfirebase-cloud-messaging

解决方案


我得到了它的解决方案,我创建了全局变量,每次setBackgroundMessageHandler函数调用我都更新它

var myUrl = "";
const messaging = firebase.messaging()
messaging.setBackgroundMessageHandler(function (payload) {
    console.log('[firebase-messaging-sw.js] Received background message', payload.data);
    const notification = payload.data;
    const notificationTitle = notification.title;
    const notificationOptions = {
        body: notification.message,
        icon: notification.icon || "/images/icon.png"
    };
    myUrl = notification.url;
    self.addEventListener('notificationclick', function(event) {
        event.waitUntil(self.clients.openWindow(myUrl));
        event.notification.close();
    });
    return self.registration.showNotification(notificationTitle, notificationOptions);
});

推荐阅读