Web Push Notification (using service worker) - javascript

Am following this project to add web push notifications using service-worker
Push Notifications and ASP.NET Core and the complete project Demo.AspNetCore.PushNotifications. Everything works fine, my only problem here is that when I send 2 or more notifications only for the last notification received, On click fires (self.addEventListener('notificationclick', function (event) {...) in the service-worker. the rest they don't do nothing.
how to make it work even for older notification (I think this happens only with chrome) ??
any help would be greatly appreciated
this is my service-worker.js :
const pushNotificationTitle = 'Demo.AspNetCore.PushNotifications';
self.addEventListener('push', function (event) {
event.waitUntil(self.registration.showNotification(pushNotificationTitle, {
body: event.data.text(),
icon: '/images/push-notification-icon.png'
}));
});
self.addEventListener('notificationclick', function (event) {
console.log('[Service Worker] Notification click Received.');
event.notification.close();
event.waitUntil(
clients.openWindow('https://stackoverflow.com/')
);
});
I send two or more notifications and put breakpoint in (self.addEventListener('notificationclick').
notificationclick event is only called when i click on the last notification received !!!!!!!!

Related

How do we trigger a push notification in nodejs manually?

I have my service worker installed like the following:
self.addEventListener('install', () => {
console.log('[sw]', 'Your ServiceWorker is installed');
});
self.addEventListener('push', ev => {
console.log('[sw]', 'pushed!!', ev.data.json());
const {title, msg, icon} = ev.data.json();
self.registration.showNotification(title, {
body: msg,
icon: icon,
});
});
I can use libraries like web-push, which actually fires an push event which is captured by service worker and shows a notification on demand (uses fcm for example in case of chrome). I just want to understand is there a way in which we can send a push notification to the user ourselves from our server, primarily on nodejs?
Can it be done?

Using service worker in angularjs

How we can get event fired in service worker in our angularjs app.
Here is sample code which is working and showing notification in chrome/firefox
self.addEventListener('push', function(event) {
console.log('[Service Worker] Push Received.');
// console.log(`[Service Worker] Push had this data: "${event.data.text()}"`);
console.log(event.data);
console.log(event.data.json());
console.log(typeof (event.data.json()));
console.log(event);
window.dispatchEvent( new Event('dataisthere') );
const title = 'YummZ';
const options = {
body: 'Message Received \n ' + event.data.json().message,
icon: 'images/icon.png',
// badge: 'images/badge.png',
data : event.data.json()
};
event.waitUntil(self.registration.showNotification(title, options));
});
I tried to dispatch a window event but i got error window is undefined
when service worker get push notification, i need to notify my angular app to perform action.
NOTE: NEW TO SERVICE WORKER
Have a read on this. Havent tested it yet but I think the general idea for the solution you are looking for is there. The title says How to Send Messages Between Service Workers and Clients, so if you manage to bridge that gap, you can pretty much tell your service worker to do whatever you want.

Push Notifications with data on push Event

I am trying to push notifications using GCM,able to show notifications with hard coded data or message on Push Event.But when I tried to push custom messages using data object as Json,Push event is triggering but ,data object always shoeing as null.
Service worker code:sw.js
self.addEventListener('push', function(event) {
console.log('Received a push message', event);
console.log("event data",event.data);//here data is giving as null
var data=event.data.json();
var title= data.title||'No tiltle';
var body= data.message||'no messgae';
event.waitUntil(
self.registration.showNotification(title, {
body: body,
icon: icon,
tag: tag
})
);
});
am using third party site(requestmaker.com) to check the notifications.
format am sending like below
URL:https://android.googleapis.com/gcm/send
content-type:application/json
authorization:key=XXXXXXXXXX
below is data format
{
"registration_ids":["someid"],
"data":{"title":"hai",
"body":"hello new message"
}
}
How can i get data in Push Event and in which format i have to send data as request sothat i can get that data on push event(event.data).
You can access the data on notification click trigger event.
self.addEventListener('notificationclick', function(event) {
// here data you access from event using event.notification.data
console.log('On notification click: ', event.notification.tag);
}
From the push notification triggered, the payload data wont be sent across to the service worker. You will have to use browser auth keys while triggering the push notification for the payload to be sent across.
Please refer the documentation below for details.
https://developers.google.com/web/updates/2016/03/web-push-encryption?hl=en

Google Cloud Messaging (GCM) not working with firefox

I have this Service Worker that receives notification well with Chrome,
but it's not receiving with firefox.
the Push listener is not fired at all in firefox (by debugging it),
PS: the service worker is successfully registered, but it's not receiving notification.
what's the problem with my code?
self.addEventListener('install', function (event) {
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', function (event) {
console.log('Activated', event);
});
self.addEventListener('push', function (event) {
event.waitUntil(
fetch('/path', {
credentials: 'include',
method: 'post',
})
.then(function (response) {
return response.json()
.then(function (data) {
return self.registration.showNotification(data.title, {
body: data.body,
icon: '/images/image.png',
});
});
})
.catch(function (error) {
console.error('wrong', error);
})
);
});
Based from this documentation, if you are using the Channel Messaging API to comunicate with the service worker, set up a new message channel (MessageChannel.MessageChannel()) and send port2 over to the service worker by calling Worker.postMessage() on the service worker, in order to open up the communication channel. You should also set up a listener to respond to messages sent back from the service worker.
Make sure that you followed these steps on how to set up the GCM properly. You can also check this related link: GCM Equivalent for Firefox
Hope this helps!
You will need to share your code in the client for registering for push notifications.
With that said, once you register for push notifications, you will receive a subscription with an endpoint. In Firefox that endpoint will never be a GCM url, but a push server provided by Mozilla:
navigator.serviceWorker.ready
.then((reg) => reg.pushManager.subscribe({ userVisibleOnly: true }))
.then((subscription) => {
const endpoint = subscription.endpoint;
// endpoint will have different server values when using this code in Chrome or Firefox.
Here are key notes to be considered:
Are you registering for push notifications correctly in firefox?
Check the url for the endpoint you will need to reach for performing the push notification, is a mozilla server one?
Setup breakpoints just after the push listener to verify that you receive the push.

How to get Google Cloud Messaging response into a Service worker's event for notifications in Chrome

The message is being received and notification does pop up when I use an example text for notification.
I've set up an account with Google for push notifications on Chrome, but the response appears to be empty.
THE SERVICE WORKER
I have this on the service worker, but its empty.
self.addEventListener('push', function(event) {
//console.log('Received a push message', event);
console.log(event.data);
});
Then there's one other thing I've tried with Fetch, using the localhost url.
var url = 'http://localhost/notification/index.php?type=fg';
self.addEventListener('push', function(event) {
event.waitUntil(fetch(url).then(function(response) {
console.log(response);
return response.json();
}).then(function(data) {
console.log(data);
//'data' does't have the json from the url
})
)
});
Chrome doesn't support push payloads yet, so the first snippet will only work in Firefox (https://serviceworke.rs/push-payload.html).
Your second approach, instead, should work in any browser (https://serviceworke.rs/push-get-payload.html).

Categories

Resources