我正在尝试将数据从我的服务器发送到 FCM,以便它可以显示在我的网页的特定部分上。例如,它就像一个股票应用程序,其中的数据不断更新。我以同样的方式努力实现。到目前为止,我已将其配置为从 FCM 接收数据并且正在接收数据。但问题是它显示了喜欢的通知。我的同事正在研究同样的问题,有一个选项可以仅将数据发送到 Android 应用程序并隐藏要显示的通知。同样,我想在网络上听到它,但我无法做到。
(function () {
// Initialize Firebase
var config = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "test-xxxxxxxx.xxxxxxxx.com",
databaseURL: "https://xxxxxx-xxxxxxxx.firebaseio.com",
projectId: "xxx-469e9",
storageBucket: "",
messagingSenderId: "xxxxxx"
};
firebase.initializeApp(config);
// Retrieve Firebase Messaging object.
const messaging = firebase.messaging();
messaging.requestPermission()
.then(function() {
console.log('Notification permission granted.');
return messaging.getToken();
})
.then(function(token) {
console.log(token);
})
.catch(function(err) {
console.log('Unable to get permission to notify.', err);
})
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
}());
在 firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.3.1/firebase-messaging.js');
// Initialize Firebase
var config = {
apiKey: "xxxxxx",
authDomain: "xxxx-xxxxxxxxxx.com",
databaseURL: "https://xxx-xxx.firebaseio.com",
projectId: "xxxx-xxxxxxxxxx",
storageBucket: "",
messagingSenderId: "xxxxxxxxxxxx"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
最佳答案
一种破解方法是在...之后关闭通知
messaging.setBackgroundMessageHandler(function (payload) {
var realPush = true;
if(realPush)
{
const notificationOptions = {
body: "It is a REAL push",
data:"true"
};
//We display the notification
return self.registration.showNotification(title, notificationOptions);
}else
{
const notificationOptions = {
body: "It is a SILENT push",
data:"false"
};
//We display a fake notification
return self.registration.showNotification('To delete',notificationOptions).then(function () {
self.registration.getNotifications().then(notifications => {
console.log(notifications);
for (var i =0;i<notifications.length;i++)
{
if(notifications[i].data != "true")
{
//then we destroy the fake notification immedialtely !
notifications[i].close();
}
}
})
});
}
});
realPush参数当然是你自己管理的
关于javascript - FCM WEB 仅接收数据并隐藏通知部分或禁用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46393388/