Using service worker in angularjs - javascript

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.

Related

Web Push Notification (using service worker)

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 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?

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.

Receive notifications 24/7 via service-worker.js in Chrome

I've been doing push notifications,
when I register the page then test it via curl commands, i received the notification!
However after a while (maybe 1-2 minutes), when I close the tab that the push notifications scope has been registered, then test the notifications again, i cant receive the notifications. This usually happens more in google Chrome in mobiles.
The workaround I did in here is that i need to go to the page of the scoped page first, then when I test the notification again, it now works. Though i cant have this because I need the clients to receive notifications without being on the site all the time.
Here are my push event in service worker
self.addEventListener('push', function(event) {
var SOME_API_ENDPOINT = "https://somewhre.com/push_notification_api/service_worker_endpoint";
event.waitUntil(
fetch(SOME_API_ENDPOINT, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'subscription_id=' + subscriptionId
}).then(function(response) {
return response.json().then(function(data) {
var title = data.notification.title;
var message = data.notification.message;
var icon = base + "assets/images/logo_notification.png";
var notificationTag = data.notification.url;
// var notificationTag = 'https://google.com'; //data.notification.tag;
return self.registration.showNotification(title, {
body: message,
icon: icon,
tag: notificationTag
});
});
})
);
});
How do i make my service workers 24/7 even though i am not in the page of the scope in the registration of SW?
Do I need to use eventListeners 'install', 'activate' and 'fetch'?
Service workers appear to persist but really don't - a new instance spins up in response to events. This will be the case when restarting on mobile to handle a push event, but there are also suggestions that busy service workers should allow multiple instances in parallel.
Your subscriptionId is a global parameter, so it may well be undefined by the time your push event fires.
To fix this you need to retain the subscriptionId in some kind of storage (mayber IndexedDB).
I also think in order for a service worker to persist it needs to have an install event and that event needs to succeed.

get and show push data from serviceworker in chrome

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...*/);
});
});

Categories

Resources