我想使用Firebase发送和接收通知,我可以将消息从Web发送到Firebase并将其接收到App android。现在,我想收到有关浏览器桌面的通知,但是它不起作用
1)将脚本添加到index.html
<script src="https://www.gstatic.com/firebasejs/5.8.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.0/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "AIzaSyDQSLErZKGEFFGFGFGFGHGH",
authDomain: "fdfdfdfdfd.firebaseapp.com",
databaseURL: "https://fdfdfdfdfdf.firebaseio.com",
projectId: "fdfdotifications",
storageBucket: "dfdfdfdfdfdfdf.appspot.com",
messagingSenderId: "665588478878"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.requestPermission().then(function() {
console.log('permissions ok');
return messaging.getToken();
// Do something with the granted permission.
})
.then(function (token) {
console.log(token)
})
.catch(function (err) {
console.log(err)
});
messaging.onTokenRefresh(function() {
messaging.getToken()
.then(function(refreshedToken) {
console.log('Token refreshed.');
})
.catch(function(err) {
console.log('Unable to retrieve refreshed token ', err);
});
});
messaging.onMessage(function(payload) {
console.log("Message received. ", payload);
// ...
});
//
</script>
2)将服务工作者(firebase-messaging-sw.js)添加到根目录
importScripts('https://www.gstatic.com/firebasejs/5.8.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.8.0/firebase-messaging.js');
var config = {
apiKey: "AIzaSyDQSLErZKGEhKoUxn4",
authDomain: "dfdfdfdfdf.firebaseapp.com",
databaseURL: "https://ddfdfdfdfd.firebaseio.com",
projectId: "kdfdfdfdinotifications",
storageBucket: "fdfdfdnotifications.appspot.com",
messagingSenderId: "696955855555"
};
firebase.initializeApp(config);
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Background Message Title';
const notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
浏览器生成令牌,但未收到来自Firebase的通知。