【问题标题】:Firebase push notifications click does not workFirebase 推送通知点击不起作用
【发布时间】:2020-11-04 19:04:22
【问题描述】:

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

{
  "message": {
    "token": "8888****usertoken****8888",
    "notification": {
      "title": "Background Message Title",
      "body": "Background message body"
    },
    "webpush": {
      "fcm_options": {
        "link": "https://dummypage.com"
      }
    }
  }
}

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

我使用的是 8.0.0 版

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

我尝试了实现messaging.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));
});

【问题讨论】:

    标签: javascript firebase google-chrome push-notification firebase-cloud-messaging


    【解决方案1】:

    原来我将整个 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" 
          }
        }
      }
    }
    

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

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

    【讨论】:

    • 如果您从请求对象中删除了 data 属性,那么您的 handleClick 函数是什么样的,或者甚至需要它?肯定会为此苦苦挣扎。
    • 看起来像上面的 webpush 属性。单击句柄会将您带到您在链接属性中定义的任何位置。请注意,链接属性需要只是相对路径,您不能指定域。您可以通过查询字符串传递数据,例如 /mypage?mydata=1&user=12345
    • 这样做你不需要定义一个函数来处理点击,它是为你定义的。它对我来说效果更好,因为当我指定它时,它有时会显示两条消息,而且我还有其他问题。
    • 它看起来就像你描述的那样一直在工作,除了点击通知仍然没有做任何事情。我想知道是不是因为我使用的是旧版 HTTP API。
    • 我已经尝试过 legacy,但它对我不起作用,可能是因为我做错了什么。我有上面的解决方案在新的 API 上工作。我快速浏览了遗留 API 文档,我认为您应该查看 click_action 方法。firebase.google.com/docs/cloud-messaging/http-server-ref
    【解决方案2】:

    我遇到了同样的问题。我添加了一个notificationclick 事件处理程序。您可以在通知事件中使用data 参数来打开一个新选项卡或聚焦已打开的选项卡。

    您已经拥有的代码很好,现在添加监听器如下所示:

    // messaging.onBackgroundMessage(...);
    
    function handleClick (event) {
      event.notification.close();
      // Open the url you set on notification.data
      clients.openWindow(event.notification.data.url)
    }
    self.addEventListener('notificationclick', handleClick);
    

    这些资源可能会有所帮助

    【讨论】:

    • 您好乔纳森,感谢您的回复。除非我使用“self.registration.showNotification”引发我自己的事件并且如果我这样做通知触发两次,否则“notificationclick”不会触发。但我发现我做错了什么我只需要将相对路径传递给 fcm_options.link。不是我正在做的整个 URL。我会用对我有帮助的来更新我的问题。感谢您的帮助。
    • 你知道为什么通知会触发两次吗?我有同样的问题。我什至注释掉了整个消息传递.onBackgroundMessage((payload) =>... 处理程序,我现在只收到第一个通知,但没有想要在该处理程序中添加的所有属性。
    【解决方案3】:

    通知正在使用legacy API,但不幸的是,单击通知仍然没有任何作用。这是我发送通知的代码。

    var notification = {
      'title': title,
      'body': body,
      'icon': 'hourglass.png',
      'click_action': router.resolve(route).href
    }
    var payload = {
      'notification': notification,
      // 'webpush': {
      //   'fcm_options': {
      //     'link': '/' + router.resolve(route).href
      //   }
      // }
    }
    if(registrationIds.length == 1) {
      payload['to'] = registrationIds[0]
    } else if( registrationIds.length > 1){
      payload['registration_ids'] = registrationIds
    }
    return new Promise((resolve, reject) => {
    
      if (registrationIds.length) {
        fetch('https://fcm.googleapis.com/fcm/send', {
          'method': 'POST',
          'headers': {
            'Authorization': 'key=' + key,
            'Content-Type': 'application/json'
          },
          'body': JSON.stringify(payload)
        }).then(function(response) {
          resolve(true)
        }).catch(function(error) {
          console.error('sendNotification error', error);
          reject(false)
        })
    
      }
      else {
        console.log('This timer has no registered clients.')
        reject(false)
    
      }
    
    })
    

    编辑:我认为我的大部分困惑源于使用 V1 API 查找示例并将它们与旧 API 混合。我需要click_action 而不是有效载荷中的fcm_options.link。我更新了我的代码,现在正在按预期工作。

    【讨论】:

      猜你喜欢
      • 2017-04-29
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多