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?
Related
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 !!!!!!!!
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.
I would like to know if it's possible to show the same notification when my website is in foreground, as when it is in background. I don't want to personalize the looks of the notification, I want to reuse it exactly how it is.
Right now, I'm handling the arrival of the notification using this function:
function messageReceived(payload) {
// TODO implement actions on message received
console.log(payload);
}
But I don't want to do it. Deleting this function doesn't help.
I'm not sure if there is another way to solve this, but I just created a new notification and used the payload received in the messageReceived method:
function messageReceived(payload) {
var notificationOptions = {
body: payload.notification.body,
icon: payload.notification.icon,
click_action: payload.notification.click_action
};
new Notification(payload.notification.title, notificationOptions);
}
To work on Android, notifications have to be sent from the serviceWorker.
To get the Firebase serviceWorker registration and use that to show the notification, you can do:
messaging.onMessage(function(payload) {
console.log("onMessage: ", payload);
navigator.serviceWorker.getRegistration('/firebase-cloud-messaging-push-scope').then(registration => {
registration.showNotification(
payload.notification.title,
payload.notification
)
});
});
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.
I use pushwoosh for receive push notification in my web app.
every things working well and received push message in serviceworker listener but I want give push messge data from serviceworker and process it in another js class
main.js like this:
if ('serviceWorker' in navigator) {
console.log('Service Worker is supported');
navigator.serviceWorker.register('sw.js').then(function() {
return navigator.serviceWorker.ready;
}).then(function(reg) {
console.log('Service Worker is ready :^)', reg);
// TODO
}).catch(function(error) {
console.log('Service Worker error :^(', error);
});
}
// get push message data in main.js and process it
service worker like this :
self.addEventListener('push', function(event) {
console.log('Push message', event);
var title = 'Push message';
event.waitUntil(
self.registration.showNotification(title, {
'body': 'The Message',
'icon': 'images/icon.png'
}));
});
As I mentioned in a comment, this seems a slightly odd use-case for a service worker rather than a standard worker, but:
You can have your service worker send a message to all connected clients when it gets a message pushed to it.
This answer shows a complete example of a service worker talking to clients, but fundamentally:
The pages it manages listen for messages:
navigator.serviceWorker.addEventListener('message', event => {
// use `event.data`
});
The service worker sends to them like this:
self.clients.matchAll().then(all => all.forEach(client => {
client.postMessage(/*...message here...*/);
}));
Or with ES5 and earlier syntax (but I don't think any browser supporting service workers doesn't also support arrow functions):
Page listening:
navigator.serviceWorker.addEventListener('message', function(event) {
// use `event.data`
});
Worker sending:
self.clients.matchAll().then(function(all) {
all.forEach(function(client) {
client.postMessage(/*...message here...*/);
});
});