【问题标题】:Send a notificaion from android app to web app via firebase cloud message [duplicate]通过firebase云消息从android应用程序向网络应用程序发送通知[重复]
【发布时间】:2020-01-21 06:24:13
【问题描述】:

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

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

【问题讨论】:

标签: javascript firebase firebase-cloud-messaging


【解决方案1】:

创建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);
 });

你可以关注这个 tut:Web Push Notification with Firebase

【讨论】:

  • 谢谢你的详细回答,我会试试这个 tut
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-16
  • 2019-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-06
相关资源
最近更新 更多