I'm sending push notifications to my website users when they (for example) receive a private message.
That notification goes to all browsers subscribed for that user. So could be desktop, mobile, work computer etc.
What I would like to do is close all the sent notifications once the user has a read a message.
So user logs in on mobile, reads the private message - at this point I want all the previously sent notifications for that PM to be closed/cancelled.
Is this possible?
Thanks in advance!
Matt
Yes this is possible, but not silently. For example, Chrome will replace the notification with a new one saying "This site has been updated in the background".
There are two separate APIs: the Push API which "gives web applications the ability to receive messages pushed to them from a server", and the Notification API which "is used to configure and display desktop notifications to the user".
The Notification API provides Notification.close(), which cancels the display of a notification.
You can use the Push API to trigger Notification.close(). Here's a sample which should go in your service worker:
self.addEventListener('push', async event => {
const data = event.data.json();
if (data.type === 'display_notification') {
self.registration.showNotification(data.title, data.options);
} else if (data.type === 'cancel_notification') {
const notifications = await self.registration.getNotifications({
tag: data.notificationTag
});
for (notification of notifications) {
notification.close();
}
} else {
console.warn("Unknown message type", event, data);
}
});
However! This design means that your cancel_notification message won't display a notification. This violates some browser policies, for example Chrome will display a new notification saying "This site has been updated in the background".
Related
I have recently updated my app to flutter for cross platform availability but I am having trouble receiving push notifications.
When I send an "alert" to the backend, users should be notified that someone sent out an alert.
Right now when I call the SendFCMNativeNotificationsAsync method, I always get an enqueued response (when I only had an Android version they always said successful).
private async Task sendNotifAsync(Alert alert)
{
Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
HttpStatusCode ret = HttpStatusCode.InternalServerError;
var cafe = cafeRepository.GetById(alert.CafeId);
var message = alert.UserName + " needs help in " + cafe.Name;
var notif = "{ \"notification\":{\"title\":\"Somebody needs help\",\"body\":\""+message+"\"},\"data\" : {\"message\":\"" + "From " + alert.UserName + ": " + message + "\"}}";
outcome = await Notifications.Instance.Hub.SendFcmNativeNotificationAsync(notif);
}
This is the code I use to call the notificationhub in my backend.
The weird thing is that when I try to send a test notification via firebase console, it works as expected, so I don't really know where to look right now to fix this issue.
To send push notification to a Flutter application targeting Android and iOS, first we need to handle device registration for the client using the latest and best Installation approach using an ASP.NET Core Web API backend. Check this Registration management document more further details.
There can be many reasons why you are facing this issue, it may be due to Notification Hubs misconfiguration or may be for Application issue due to invalid registration and Push notification service could also be the issues.
Since you are getting notification from firebase console, push notification service should not be an issue. Still you can use the EnableTestSend property while you initialize NotificationHubClient to get a detailed status about push notification service errors that occur if any when the notification is sent.
bool enableTestSend = true;
NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(connString, hubName, enableTestSend);
var outcome = await hub.SendWindowsNativeNotificationAsync(toast);
Console.WriteLine(outcome.State);
foreach (RegistrationResult result in outcome.Results)
{
Console.WriteLine(result.ApplicationPlatform + "\n" + result.RegistrationId + "\n" + result.Outcome);
}
I would suggest to read the Diagnose dropped notifications in Azure Notification Hubs document from Microsoft to do some self-diagnosis and solve the problem you are facing. Also read the Send push notifications to Flutter apps using Azure Notification Hubs via a backend service document for more information.
I have integrated the Huawei Push kit to my app and when I trigger a notification from Huawei Push Kit Console, I can receive the notification when the app is in background. However, when our system backend triggers Huawei API to push notifications, it doesn't appear when the app is in the background.
Following code is getting executed despite the app is in foreground or background but Notification parameters such as Title etc, coming as null. Notification object itself is not null.
Contents of the JSON message can be received as a single String from remoteMessage.getData() but values does not mapped to respective fields.
public class HuaweiNotificationHandler extends HmsMessageService{
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.i(TAG, "getData: " + remoteMessage.getData()
RemoteMessage.Notification notification = remoteMessage.getNotification();
if (notification != null) {
Log.i(TAG, "getTitle: " + notification.getTitle()
}
}
}
Our backend executes this API provided by Huawei to send data messages.
This is the format of our JSON
{
"collapseKey":"dummykey",
"priority":"high",
"delayWhileIdle":false,
"dryRun":false,
"sound":"",
"contentAvailable":true,
"data":{
"data":{
"type":"A",
"id":"1111111",
"entity":"0",
"url":""
},
"restrictedPackageName":"com.aa.bb.cc" // this package name is exactly same as the huawei app package registered
},
"notification":{
"title":"Notification Title",
"icon":"ic_launcher",
"body":"Message"
}
}
UPDATE
Sample code of a typical data message:
{
"validate_only": false,
"message": {
"data": "{'param1':'value1','param2':'value2'}",
"token": [
"pushtoken1",
"pushtoken2"
]
}
}
For Details,see Docs.
Push Kit supports two types of messages: notification messages and data messages.
After a device receives a data message, the device transfers it to your app instead of directly displaying the message. Your app then parses the message and triggers the corresponding action. Push Kit only functions as a channel, and the delivery of data messages depends on the resident status of your app. However, notification messages can still be delivered even if your app is not launched.
For the sake of saving power and not disturbing users, your app will not be launched by Push Kit after being stopped, and no data messages can be delivered to your app. In this case, you can determine whether to use notification messages based on your services.
From: https://stackoverflow.com/a/64100678/14006527
Alternatively, you can set High-priority data messages to forcibly launch your stopped app to receive and process the messages.
We currently have an Ionic and Firebase project that we coded. In this project, we want to use push notifications. But our trouble is:
We are looking for a push notification plugin, like WhatsApp application. For example, when we send a message to a person, we want the notification to go to the person we're texting from, not everyone. But we couldn't find a free way to do that. Do you have any suggestions? Thank you.
Firebase Cloud Messaging By using cordova-plugin and ionic-native:Ref. Url
import { FCM } from '#ionic-native/fcm/ngx';
constructor(private fcm: FCM) {}
this.fcm.getToken().then(token => {
//you can store device token in firebase, later you can target push notification from firebase console this token id
backend.registerToken(token);
});
this.fcm.onNotification().subscribe(data => {
if(data.wasTapped){ / * true , means the user tapped the notification from the notification tray and that’s how he opened the app. */
console.log("Received in background");
} else {// false , means that the app was in the foreground (meaning the user was inside the app at that moment)
console.log("Received in foreground");
};
});
this.fcm.onTokenRefresh().subscribe(token => {
//update device token
backend.registerToken(token);
});
I don't recommend you to use FCM plugin. It has no methods to manage your notifications in your app (clear all or clear some special notification.
It is better to use phonegap-push-plugin or One Signal
I have created one of the mobile application using ionic 1 and firebase. Now I want to create a notification categories like channel where user can select which notification they needed.
Here I have shared the code for push notification which i have used and this code is working , i want to create the notification categories, the above code is working for push notification for my mobile application.
Now I need a help that how can I create the channel notification categories in my mobile application
FCMPlugin.onNotification(function(data){
if(data.wasTapped){
//Notification was received on device tray and tapped by the user.
alert( JSON.stringify(data) );
}else{
//Notification was received in foreground. Maybe the user needs to be notified.
alert( JSON.stringify(data) );
}
});
I am making a google action.I have one scenario where calculation requires some time in cloud fulfillment but i don't want to keep user waiting for answer.
I want to respond to user whenever my answer is ready even when conversation with user is ended i want to send my answer in notification or something like that.
I just found this on google actions documents.
https://developers.google.com/actions/assistant/updates
Is this possible in google actions and how?
What you mean here is notifications. You can use it but please pay attention to the warning at the top of the link you provided: "Updates and notifications are currently in Developer Preview. You can build apps using the features described in this article, but you can't currently publish them".
As for the steps to crated a daily notification:
Navigate to your actions.intent.CONFIGURE_UPDATES intent.
Under Responses, go to the Google Assistant tab, click Add Message Content, and select Custom Payload.
In the "Custom Payload" box, add the following code to call the AskToRegisterDailyUpdate helper. Swap INTENT_NAME to the intent that you want to be invoked when the user interacts with your notification.
{
"google": {
"system_intent": {
"intent": "actions.intent.REGISTER_UPDATE",
"data": {"#type": "type.googleapis.com/google.actions.v2.RegisterUpdateValueSpec",
"intent": "INTENT_NAME",
"triggerContext": {
"timeContext": { "frequency": "DAILY" }
}
}
}
}
}
If using a webhook, you can call this API directly via the client library:
appMap.set('setup_update', function(app) {
app.askToRegisterDailyUpdate('INTENT_NAME');
})
})
Add one more intent called "finish_update_setup" and enter actions_intent_REGISTER_UPDATE as its Event.
Set the intent's Action to "finish_update_setup" as well.
In your webhook, open index.js and add the following. Replace Ok, I'll start giving you daily updates and Ok, I won't give you daily updates. with whatever response you want to give the user:
appMap.set('finish_update_setup', function(app)) {
if (app.isUpdateRegistered()) {
app.tell("Ok, I'll start giving you daily updates.");
} else {
app.tell("Ok, I won't give you daily updates.");
}
}
Deploy the webhook to Firebase Functions and enable webhook fulfillment in Dialogflow.
If you want to see how to create a simple notification (not daily one) - please check this doc on push notifications.
If you don't have an immediate reply to send but expect one soon-ish what you do is return a "promise". When you are in a position to reply, "fulfilling" the promise causes your reply to be delivered. I don't know what the actual timeout is but in my case I'm pretty sure at least a few second delay is allowed.
As for the updates or notifications, the API is there but the docs say you can't deploy an Action to production using them. There is a slightly cryptic comment to "contact support" if you need them.
One of these days I might try.