我能够在控制台上接收并显示通知,但它不会显示在浏览器(chrome)中。
我遵循的步骤是:
FirebaseMessaging.instance.getToken().then((String token) {
debugPrint('Token: $token');
});
#!/bin/bash
DATA='{"notification": {"body": "This is a message","title": "Marcelo"}, "priority": "high", "data": {"click_action": "FLUTTER_NOTIFICATION_CLICK", "id": "1", "status": "done"}, "to": "eMkcLmwSSBeWXS_YEB-b_R:APA91bG2pyrDVr0BBoya0rQET0vfwTVE3aTeQsoqsxVMK70ypm6aaa-pNdX9uQ5BgEsoQGuVoe-EpeePJB8Q7XUfTvrTlgtRW8HSZ3qOaxotFUSaq8JqrgRtummIOnMFYUGqtg-sMP8Y"}'
curl https://fcm.googleapis.com/fcm/send -H "Content-Type:application/json" -X POST -d "$DATA" -H "Authorization: key=AAAAKavk7EY:APA91bEtq36uuNhvGSHu8hEE-EKNr3hsgso7IvDOWCHIZ6h_8LXPLz45EC3gxHUPxKxf3254TBM1bNxBby_8xP4U0pnsRh4JjV4uo4tbdBe2sSNrzZWoqTgcCTqmk3fIn3ltiJp3HKx2"
收到成功回复
{"multicast_id":5695802004264337317,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1615137996888514%2fd9afcdf9fd7ecd"}]}
FirebaseMessaging.onMessage.listen((RemoteMessage message)
{
RemoteNotification notification = message.notification;
if (notification != null) {
print('Title ${notification.title}');
print('Body ${notification.body}');
}
});
但是浏览器不显示通知。我错过了什么?
要在webflutter前台显示通知,可以使用dialog之类的东西,要在后台显示,可以使用以下脚本:
messaging.onBackgroundMessage(function(payload) {
console.log('Received background message ', payload);
const notificationTitle = payload.notification.title;
const notificationOptions = {
body: payload.notification.body,
};
self.registration.showNotification(notificationTitle,
notificationOptions);
});
要自定义后台通知显示,请阅读以下链接: 显示通知
请务必获得必要的许可
NotificationSettings settings =
await _firebaseMessaging.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: true,
);
debugPrint('User granted permission: ${settings.authorizationStatus}');
如果 Windows 中仍未显示通知: 设置=>通知和操作=>Google Chrome
切换至开启状态。
static onMessageWebNotification(NotificationData notificationData, String payloadData) {
html.window.navigator.serviceWorker.ready.then((registration) {
var notificationTitle = notificationData.title;
var notificationOptions = {
'body': notificationData.body,
'data': notificationData
};
registration.showNotification(
notificationTitle,
notificationOptions,
);
});
}
要在 Flutter Web 上显示通知,并且当 Web 应用程序位于前台时,您必须通过 flutter 端并使用 universal_html 或 html 包来处理它
void setupForegroundNotificationHandling() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
if (message.notification != null) {
showNotification(message.notification!.title ?? "", message.notification!.body ?? "");
}
});
}
void showNotification(String title, String body) {
if (html.Notification.permission == "granted") {
html.Notification(title, body: body);
} else {
html.Notification.requestPermission().then((permission) {
if (permission == "granted") {
html.Notification(title, body: body);
} else {
debugPrint("Notification permission denied");
}
});
}
}