要开始使用 FCM,请构建最简单的用例:当应用程序在设备后台运行时,向特定用户发送通知消息。此页面列出了实现此目的的所有步骤,从设置到验证——如果您为 FCM设置了 JavaScript 客户端应用程序,它可能涵盖您已经完成的步骤。
设置开发工具包
如果您还没有,请将 Firebase 添加到您的 JavaScript 项目中。
访问注册令牌
当您需要检索应用程序实例的当前注册令牌时,首先使用Notification.requestPermission()
向用户请求通知权限。如图所示调用时,如果授予权限则返回令牌,如果拒绝则拒绝承诺:
function requestPermission() { console.log('Requesting permission...'); Notification.requestPermission().then((permission) => { if (permission === 'granted') { console.log('Notification permission granted.');
FCM 需要一个firebase-messaging-sw.js
文件。除非您已经有一个firebase-messaging-sw.js
文件,否则请使用该名称创建一个空文件并将其放在您域的根目录中,然后再检索令牌。您可以稍后在客户端设置过程中向该文件添加有意义的内容。
要检索当前令牌:
Web version 9
import { getMessaging, getToken } from "firebase/messaging"; // Get registration token. Initially this makes a network call, once retrieved // subsequent calls to getToken will return from cache. const messaging = getMessaging(); getToken(messaging, { vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => { if (currentToken) { // Send the token to your server and update the UI if necessary // ... } else { // Show permission request UI console.log('No registration token available. Request permission to generate one.'); // ... } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); // ... });
Web version 8
// Get registration token. Initially this makes a network call, once retrieved // subsequent calls to getToken will return from cache. messaging.getToken({ vapidKey: '<YOUR_PUBLIC_VAPID_KEY_HERE>' }).then((currentToken) => { if (currentToken) { // Send the token to your server and update the UI if necessary // ... } else { // Show permission request UI console.log('No registration token available. Request permission to generate one.'); // ... } }).catch((err) => { console.log('An error occurred while retrieving token. ', err); // ... });
获得令牌后,将其发送到您的应用服务器并使用您喜欢的方法存储它。
发送测试通知消息
在目标设备上安装并运行该应用程序。在 Apple 设备上,您需要接受接收远程通知的许可请求。
确保应用程序在设备的后台运行。
在 Firebase 控制台中,打开消息页面。
如果这是您的第一条消息,请选择创建您的第一个营销活动。
- 选择Firebase Notification messages并选择Create 。
否则,在“活动”选项卡上,选择“新建活动” ,然后选择“通知”。
输入消息文本。所有其他字段都是可选的。
从右窗格中选择发送测试消息。
在标记为添加 FCM 注册令牌的字段中,输入您在本指南上一节中获得的注册令牌。
选择测试。
选择测试后,目标客户端设备(应用程序在后台)应该会收到通知。
下一步
向前台应用程序发送消息
在您的应用程序处于后台时成功发送通知消息后,请参阅在 JavaScript 客户端中接收消息以开始向前台应用程序发送消息。
超越通知消息
要超越通知消息并向您的应用程序添加其他更高级的行为,请参阅: