通过 Firebase Cloud 消息将通知从安卓应用发送到网络应用



我试图做的是在Android应用程序中创建一个按钮,当单击按钮时,它会通过FCM(Firebase云消息传递(向Web App(javascript(发送通知。 我已经完成了从网络应用程序向安卓应用程序发送消息/通知。我创建了一个 REST API( spring boot(,它可以向主题发送通知,然后在 web 应用程序中,我调用此 api,将一些数据放入其中,在 android 应用程序中,我创建了一个服务来接收带有主题的通知。

现在,我想从安卓应用程序调用我的 api(单击按钮时(并向网络应用程序发送通知。 我想知道如何使用 javascript 在 Web 应用程序中订阅主题,并在将消息发送到该主题时接收消息/通知。

创建一个firebase.js

<script>
var config = {
messagingSenderId: '<replace-with-your-sender-id>'
};
firebase.initializeApp(conyou);
</script>

现在,您必须创建firebase-messaging-sw.js并将其放置在Web文件夹的根目录

importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/3.9.0/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the
// messagingSenderId.
firebase.initializeApp({
'messagingSenderId': 'YOUR-SENDER-ID'
});
// Retrieve an instance of Firebase Messaging so that it can handle background
// messages.
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: '/itwonders-web-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});

您还必须请求用户许可才能显示通知:

const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted." 
console.log("Notification permission granted.");
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});

检索 FCM 的通知令牌

const messaging = firebase.messaging();
messaging
.requestPermission()
.then(function () {
MsgElem.innerHTML = "Notification permission granted." 
console.log("Notification permission granted.");
// get the token in the form of promise
return messaging.getToken()
})
.then(function(token) {
// print the token on the HTML page
TokenElem.innerHTML = "token is : " + token
})
.catch(function (err) {
ErrElem.innerHTML = ErrElem.innerHTML + "; " + err
console.log("Unable to get permission to notify.", err);
});

您可以按照以下方式进行操作: 使用Firebase进行网络推送通知

相关内容

最新更新