Firebase 推送通知点击不起作用

Bru*_*lli 2 javascript google-chrome push-notification firebase firebase-cloud-messaging

我在使用 firebase 实现通知时遇到问题。点击事件不起作用。我正在使用 HTTP 1 版本发送不记名令牌。

{
  "message": {
    "token": "8888****usertoken****8888",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我还尝试过 click_action、action 和许多其他变体,但都不起作用。

我使用的是8.0.0版本

根据此链接https://firebase.google.com/docs/cloud-messaging/js/send-multiple上找到的文档,我应该能够使用 fcm_options 来实现它。

我尝试了一种实现 messages.onBackgroundMessage 的解决方法,但是当我实现此方法并使用 self.registration.showNotification 时,通知会显示两次。一个由浏览触发,另一个由此代码触发。

注册 self.addEventListener('notificationclick' 似乎仅在我实现 onBackgroundMessage 时才起作用。

我遵循了文档,但这让我发疯。

这是我的服务人员代码:

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

var firebaseConfig = {
    apiKey: "xxxxxx",
    authDomain: "xxxxxxxx.firebaseapp.com",
    databaseURL: "https://xxxxxx.firebaseio.com",
    projectId: "xxx-xxx",
    storageBucket: "xxx-xxx.appspot.com",
    messagingSenderId: "222222222",
    appId: "1:2222:web:22222"
};
console.log("fire base messaging")

firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();


messaging.onBackgroundMessage(function (payload) {
    console.log("onBackgroundMessage", payload)
    var dataFromServer = payload.notification;
    var notificationTitle = dataFromServer.title;
    var notificationOptions = {
        body: dataFromServer.body,
        image: dataFromServer.image,
        data: {
            url: "https://google.com"
        }
    };
    return self.registration.showNotification(notificationTitle,
        notificationOptions);
});

////Code for adding event on click of notification
self.addEventListener('notificationclick', function (event) {
    console.log("notificationclick", event)
    var urlToRedirect = event.notification.data.url;
    event.notification.close();
    event.waitUntil(self.clients.openWindow(urlToRedirect));
});
Run Code Online (Sandbox Code Playgroud)

Bru*_*lli 10

结果我将整个 URL 传递给 webpush.fcm_options.link = "https://google.com",我所要做的就是仅传递相对路径,如 webpush.fcm_options.link = "/mypage"。

所以发送的请求会是这样的:

{
  "message": {
    "token": "8888****usertoken****8888",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "/mypage" 
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

我在文档中没有看到这只是相对路径。它甚至声明需要 HTTPS。我花了几个小时研究这个,我希望它对其他人有帮助。

https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#WebpushFcmOptions