PWA notification grouping - push-notification

I have created a PWA and implemented push notifications.
From what I understand notifications can be replaced using tag and behaviour controlled using renotify. Google documentation here.
This may be a good way to keep down the amount of displayed notifications, but is there a way to group notifications in a PWA?
In native apps I have noticed that notifications get "grouped" or "stacked" into one notification if there are more than a certain amount of notifications. Can this be achieved in a PWA?
Code for showing a push notification:
self.addEventListener('push', function (event){
console.log('Push Notification received', event)
const defaultData = {title: 'New!', content: 'Something new happened!', openUrl: '/'}
const data = (event.data) ? JSON.parse(event.data.text()) : defaultData
var options = {
body: data.content,
icon: '/img/ico/manifest-512.png',
badge: '/img/ico/badge96.png',
// tag: 'myTag',
// renotify: true,
data: {
url: data.openUrl
}
}
event.waitUntil(
self.registration.showNotification(data.title, options)
)
})
Kind regards /K

Related

HMS cancel notification with tag not working ( (HMS push kit)

I am integrating Huawei Push Kit (https://pub.dev/packages/huawei_push) in Flutter application.
I test to schedule a notification to notify every minutes in my Huawei phone, and I able to get the notification as expected. But when I tried to cancel the notification with clearNotification() function (shown below), the notification seem like not cancelled. Wondering do I miss out anything?
scheduleLocalNotification() async {
try {
Map<String, dynamic> localNotification = {
HMSLocalNotificationAttr.TITLE: 'Notification Title',
HMSLocalNotificationAttr.MESSAGE: 'Notification Message',
HMSLocalNotificationAttr.TICKER: "OptionalTicker",
HMSLocalNotificationAttr.TAG: "push-tag",
HMSLocalNotificationAttr.BIG_TEXT: 'This is a bigText',
HMSLocalNotificationAttr.SUB_TEXT: 'This is a subText',
HMSLocalNotificationAttr.LARGE_ICON: 'ic_launcher',
HMSLocalNotificationAttr.SMALL_ICON: 'ic_notification',
HMSLocalNotificationAttr.COLOR: "white",
HMSLocalNotificationAttr.VIBRATE: true,
HMSLocalNotificationAttr.VIBRATE_DURATION: 1000.0,
HMSLocalNotificationAttr.ONGOING: false,
HMSLocalNotificationAttr.DONT_NOTIFY_IN_FOREGROUND: false,
HMSLocalNotificationAttr.AUTO_CANCEL: false,
HMSLocalNotificationAttr.INVOKE_APP: false,
HMSLocalNotificationAttr.ACTIONS: ["Yes", "No"],
HMSLocalNotificationAttr.REPEAT_TYPE: RepeatType.MINUTE,
HMSLocalNotificationAttr.FIRE_DATE:
DateTime.now().add(Duration(minutes: 1)).millisecondsSinceEpoch,
};
Map<String, dynamic> response =
await Push.localNotificationSchedule(localNotification);
print("Scheduled a local notification: " + response.toString());
} catch (e) {
print("Error: " + e.toString());
}
}
clearNotification() async {
Push.cancelNotificationsWithTag('push-tag');
}
Currently, Huawei Push Kit does not support clearNotification() function. You can use the Sending Downlink Messages API. There is an auto_clear parameter, and you can set message display duration, in milliseconds. Messages are automatically deleted after the duration expires.
Please refer to the following code:
{
"validate_only": false,
"message": {
"android": {
"notification":{"body":"Big Boom Body!","click_action":{"type":3},"title":"Big Boom Title","auto_clear": 360000}
},
"token":[
"token1",
"token2"]
}
}
For more information, see docs
Your clearNotification function which calls Push.cancelNotificationWithTag('push-tag') is async.
Possibility is Push.cancelNotificationWithTag might get called before.
Either call it directly and not thru async function or add await.

How open a specific screen show the detail of the notification in react native

How to skip/open a specific screen based notification. Example: When a user clicks on the notification, the application should open and go directly to the notifications page instead of the home page.
when i was using react-native-push-notification i mannage to get the text of my notification this way :
componentWillMount() {
var _this = this;
PushNotification.configure({
onRegister: function(token) {
_this.props.InitToken(token.token);
},
onNotification: function(notification) {
setTimeout(() => {
if(!notification['foreground']){
_this.props.InitNotif(notification['message']);
}
}, 1);
PushNotification.localNotificationSchedule({
title: 'Notification with my name',
message: notification['name'], // (required)
date: new Date(Date.now()) // in 60 secs
});
},
// ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: "YourID",
});
}
where
_this.props.InitToken(token.token);
and
_this.props.InitNotif(notification['message']);
are redux based function that update your state with the notification token and message. When you'r state is updated whith the notification message your can change route ou display the message on screen.
PS:
i dont know if it was the good way but i was working
componentWillMount() is depreciated.

react native push notification doesn't show banner (pop on screen) when app is in background or closed

I'm using react-native-push-notification and followed its documents. it works fine when the app is in the foreground but when the app is in the background and I try to send a notification from firebase console, just shown a small icon of the app in statusbar but doesn't show banner
I tried to add a new channel but still not working
componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectivityChange);
PushNotification.configure({
// (optional) Called when Token is generated (iOS and Android)
onRegister: function(token) {
console.log( 'TOKEN:', token );
},
// (required) Called when a remote or local notification is opened or received
onNotification: function(notification) {
console.log( 'NOTIFICATION:', notification );
Platform.OS === 'ios' ? notification.finish(PushNotificationIOS.FetchResult.NoData) : null;
},
// ANDROID ONLY: GCM or FCM Sender ID (product_number) (optional - not required for local notifications, but is need to receive remote push notifications)
senderID: Variables.GCM_SENDER_ID,
// IOS ONLY (optional): default: all - Permissions to register.
permissions: {
alert: true,
badge: true,
sound: true
},
visibility: 'public',
popInitialNotification: true,
requestPermissions: true,
});
}
try to off the power saving mode battery because is block notification on background

Firebase sw.js not respnding after closing browser

I have created firebase project for using Cloud Messaging . until now I have sent a message from backend to client successfully when the browser (chrome) is open but when I close the browser notification not sending until reopening of the browser in below code you can see my firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
firebase.initializeApp({
messagingSenderId: "My-Sender-Id"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = 'Background Message Title';
var notificationOptions = {
body: 'Background Message body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
self.addEventListener('push', function(e) {
var data;
if (e.data) {
data = JSON.parse(e.data.text()).data;
} else {
data = {};
}
var title = data.title;
var options = {
body: data.body,
icon: 'assets/custom/img/logo.png',
vibrate: [100, 50, 100],
requireInteraction: true,
data: data.data ? data.data : null,
dir: "rtl",
actions: [{
action: data.action,
title: 'open',
icon: 'images/checkmark.png'
},
{
action: 'close',
title: 'close',
icon: 'images/xmark.png'
},
]
};
e.waitUntil(
self.registration.showNotification(title, options)
);
});
self.addEventListener('notificationclick', function(event) {
console.log('On notification click: ', event.notification.tag);
event.notification.close();
if (event.action != "" && event.action != "close") {
return clients.openWindow(event.action);
}
});
how can I have notification even browser is closed?
I believe you are using service worker for FCM, and the service worker only works when the browser is open ,as service worker is responsible for handling the push notification, when the browser is closed you won't receive any push notification, Actually the push notification will appear only when the browser is opened ,or the application for which you have configured FCM is open on chrome tabs but not focused, there is one work around or you say solution for it , that is make sure the chrome browser is active in the background even after closing chrome browser.
There is option in chrome settings
Goto Settings -> Advanced -> Continue running background apps when Google Chrome is closed make sure you enable it
i have tested the code of FCM , after enabling the option you will get the notification popup.
What you are trying to achieve should be accomplished using a database like firestore. When a notification is received at the time when browser is closed, in the service worker, you should add the code to save the notification message in the firestore so that when user opens the website again, you can retrieve the messages from the firestore and can display them to user. As soon as the browser is opened, any pending notification would be saved to the database by service worker.
I believe this should be the preferred way to achieve this.

FCM: Cannot click notification

I'm using the recently release FCM messaging support for push notifications on the chrome. When my app is in the background, I get the notification but nothing happens when I click the notification. How to I specify the URL which should open when the user clicks the notification? (I understand how its done using the pure service worker concept using the notificationclick event, I want to know how to do that using FCM messaging.)
messaging.setBackgroundMessageHandler(function(payload) {
var data = payload || {};
var shinyData = decoder.run(data);
console.log('[firebase-messaging-sw.js] Received background message ', shinyData);
return self.registration.showNotification(shinyData.title, {
body: shinyData.body,
icon: shinyData.icon
})
});
What am I missing here?
click_action is not one of the possible parameters of the showNotification function.
To handle the click on the notification, define a notificationclick event handler.
For example:
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(self.clients.openWindow(YOUR_URL_HERE));
});
Marco's answer is correct.
The Firebase Messaging Library is a wrapper on top of the Web Push API.
The notification: { click_action: 'https://...' } payload will show a notification and handle the click for you. To achieve the same with data payload you should implement the notificationclick event listener (Like Marco suggested).
self.addEventListener('notificationclick', function(event) {
event.notification.close();
... Do your stuff here.
});
You can also do the same with the notificationclose event:
self.addEventListener('notificationclose', function(event) {
... Do your stuff here.
});

Resources