如何在反应js应用程序中集成fcm?

时间:2017-05-11 05:50:37

标签: reactjs firebase firebase-cloud-messaging

我想将fcm整合到react js应用程序中以提供实时聊天。要继续的任何输入吗?

2 个答案:

答案 0 :(得分:3)

我的回答是Leonardo Cardoso的相关文章的简短版本。有关详细信息,请查看他的article

将FCM添加到React应用程序非常简单。我将演示通过create-react-app生成的项目。当然,以下说明对各种React项目都是可行的。

首先,将Firebase添加到项目中。

  

npm install firebase --save

然后,我们将创建js文件来保存我们的推送通知的逻辑。让我们将其命名为push.js并在内部函数中声明以初始化firebase app

import firebase from 'firebase';
export const initializeFirebase = () => {
  firebase.initializeApp({
    // taken from your project settings --> cloud messaging
    messagingSenderId: "your messagingSenderId"
  });
}

我们将在入口点调用此函数。

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { initializeFirebase } from './push'; <-- add this

ReactDOM.render(<App />, document.getElementById('root'));
initializeFirebase(); <-- add this

要使用firebase cloud messaging,我们需要一个服务工作者。默认情况下,启动Firebase时,它将查找名为firebase-messaging-sw.js的文件。有一种方法可以创建和附加您自己的 service worker 。为简化起见,我们将使用默认方法。

因此,我们需要在服务文件的位置添加firebase-messaging-sw.js。当我们使用create-react-app时,我将其添加到公共文件夹中,其内容如下:

importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-app.js'); <-- check for last version
importScripts('https://www.gstatic.com/firebasejs/5.8.2/firebase-messaging.js'); <-- check for last version
firebase.initializeApp({
    messagingSenderId: "your messagingSenderId again"
});
const messaging = firebase.messaging();

初始设置完成。现在,您可以添加所需的功能:征求许可,发送通知或其他任何功能。 the source article中介绍了询问权限和发送通知的实现。

答案 1 :(得分:2)

我建议你看一下sample。您可能还想查看此video教程。

相关问题