get and show push data from serviceworker in chrome - javascript

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

Related

Service workers event listener - fetch

I'd created a service worker by next code:
if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
navigator.serviceWorker.register('/sw.js').then(function(registration) {
console.log('ServiceWorker registration successful with scope: ', registration.scope);
}).catch(function(err) {
console.log('ServiceWorker registration failed: ', err);
});
});
}
and get fine answer, and event 'install' emit in sw.js ok, but event 'fetch' never emit.
I use http-server (node js) with 80 (http) port, i've seen my request in DevTools Chrome and in console from http-server, but my service worker hadn't emitted any.
My service worker code:
self.addEventListener('install', () => {
console.log("event - install"); // OK
});
self.addEventListener("fetch", (e) => {
console.log("A"); // BAD
return e.request;
});
I use this code in the end of body
setTimeout(() => {
alert("S");
fetch("/svg.svg", {
method: "GET"
});
}, 10000);
serviceworker must run in https protocol but http-server create a http server
Ok, i decide my problem. I forgot to remove option 'Disable cache' in DevTools (in 'Network' tab) Chrome, i'd worked with this option yesterday.

Service worker cache storage not updated when code changes

My single page web application, is written as PWA. It's a ASP.NET Web API application, which is hosted under IIS. My application uses a service worker, which precaches my application shell. Other content is written to indexedDB or updated in the service worker cache on-the-fly, as the user clicks through the application.
I have a problem with code changes. When I update code, and refresh my browser, I can see my changes directly in the javascript and html code. When I go offline, my application falls back on the code, which is in my service worker. This code is still old code. It seems not to be updated, when i reload my application. My service worker looks like this:
const urlsToCache = ['.'
, 'index.html'
, 'favicon.ico'
, 'service-worker.js'
// More sources are cached here
];
self.addEventListener('install', function (event) {
console.log('\'Install\' event triggered.');
event.waitUntil(
caches.open(CACHE).then(function (cache) {
console.log('Application shell and content has been cached.')
return cache.addAll(urlsToCache);
}).then(function (event) {
return self.skipWaiting();
})
);
});
self.addEventListener('activate', function (event) {
console.log('\'Activate\' event triggered.');
return self.clients.claim();
});
For registering the service worker, my code looks like this:
navigator.serviceWorker.register('./service-worker.js')
.then(function (registration) {
console.log('Registered: ', registration);
registration.update();
console.log('Updated: ', registration);
resolve(registration);
}).catch(function (error) {
console.log('Registration failed: ', error);
reject(error);
});
So when the service worker get registered, it also checks for updates. However, it only updates when the service worker code itself is changed. Not when code within my application shell is changed without changing the service worker code itself.
How can i make sure that the code in my service worker is reloaded when I change my application code and refresh my page?

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.

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.

Categories

Resources