FCM / 如何处理前台和后台通知?



我使用Firebase的REST API向所有浏览器发送通知。我使用PHP发送消息,并与服务工作者一起处理结果。

我面临的问题是,每次发送通知时,我都会在浏览器中收到两个通知。一个对应于从PHP发送的通知内容(前台通知(,另一个来自服务工作者(后台通知(。

虽然我理解两者的必要性,但我只想根据上下文显示一个(上下文=浏览器是否打开(。

对于发送,我使用以下数组:

$additional["url1"]="https://www.orange.be";
$additional["url2"]="https://www.proximus.be";
$additional["url3"]="https://www.base.be";
$additional = json_encode($additional);

$fields = array(
'to'=>$to,
'notification' => [
'title' => 'new title',
'body' => 'aaa' ,
'color' => "#FF33CC",
'data'=>$additional

],
"priority" => "high",
);

在服务人员中,我有这样的:

messaging.onBackgroundMessage((payload) => {
//console.log('Messaging:');
//console.log(messaging); 
console.log('Payload:');
console.log(payload);
additional = payload.data["gcm.notification.data"];
console.log(additional)
additional = JSON.parse(additional);
console.log(additional);
const notificationTitle = payload.notification["title"]+'(bg)';
const notificationOptions = {
body: payload.notification["body"],
icon: '/firebase-logo.png'
};
self.registration.showNotification(notificationTitle,notificationOptions);
});

如果我删除最后一行(self.registration(,我只收到来自PHP的前台通知。

如何检测上下文以使用前台或后台通知,而不是同时使用两者?

感谢

后台接收的消息使用onBackgroundMessage和前台onMessage进行处理。

后台处理程序

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

前景处理器

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

我在这里找到了一个基于另一篇文章的解决方案。我从json中删除了通知,并通过变量传递了所有内容:

$fields = array(
'to'=> $to,

'data'=> [
"title"=> "My title",
"description"=>"My description ",
"link"=>"destination link",
"badge"=>"image url",
"image"=>"image url"],

"priority" => "high",
);

在服务工作者内部,我用payload.data捕获数据,并将其与通知选项关联

messaging.onBackgroundMessage((payload) => {
console.log('Messaging / bg');
console.log(messaging); 
console.log('Payload:');
console.log(payload);
additional = payload.data;
console.log(additional)
timing = Date.now();
if (typeof additional["timing"] !=="undefined")
{
timing = additional["timing"];
}
const notificationTitle =additional["title"]+'(bg)';
const notificationOptions = {
body: additional["description"],
icon: additional["image"],
image: additional["image"],
badge: additional["badge"],
eventTime: timing,
};
// DISPLAY NOTIFICATION
self.registration.showNotification(notificationTitle,notificationOptions);});

相关内容

  • 没有找到相关文章

最新更新