我正在将 Firebase 消息传递用于 Firebase 推送通知,其中
firebase_messaging: ^14.7.9
是最新版本。我知道 onBackgroundMessage
和 onMessageOpenedApp
在 Flutter Web 中不起作用。但我在任何文档中都读到 onMessage
在 Flutter Web 中运行良好。但它也不起作用。
index.html 的 onMessage 侦听器工作并打印控制台消息。但在飞镖方面onMessage
不起作用。任何帮助或建议将不胜感激。
我已经正确初始化了 Flutter Web。
首先将 firebase_core 和 firebase_messaging 添加到您的 pubspec.yaml
在 main() 函数中添加 init Firebase
await Firebase.initializeApp(
options: const FirebaseOptions(
apiKey: "xxxx",
authDomain: "xxxxx",
databaseURL: "xxxx",
projectId: "xxxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxxx",
appId: "xxxxxx"));
初始化 Firebase 后,您必须初始化 Firebase 消息传递并在浏览器中请求通知,您可以这样做
FirebaseMessaging messaging = FirebaseMessaging.instance;
messaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: true,
sound: true,
);
NotificationSettings settings = await messaging.getNotificationSettings();
将其添加到 JavaScript 文件中
importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.7.1/firebase-messaging-compat.js');
const firebaseConfig = {
apiKey: "xxxx",
authDomain: "xxxxx",
databaseURL: "xxxx",
projectId: "xxxxx",
storageBucket: "xxxx",
messagingSenderId: "xxxxx",
appId: "xxxxxx"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
将其添加到您的index.html文件中
<script>
if ('serviceWorker' in navigator) {
window.addEventListener('load', function () {
navigator.serviceWorker.register('/firebase-messaging-sw.js');
});
}
</script>
那么你基本上就可以开始了,这就是你所要做的。然后转到 https://console.firebase.google.com/u/0/project/your-project-id/messaging 并将您的 flutter web 应用程序添加到其中,并通过获取使用 wait FirebaseMessaging.instance.getToken(); 从您的应用程序获取令牌