Service workers event listener - fetch - javascript

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.

Related

Blank Service worker script

The service worker script is blank
I am trying to implement service workers into my web app however i noticed nothing was working. I get confirmation that the service worker starts however when i try to view it in the chrome tools it shows a blank document. All efforts to console log etc are unsuccessful which is leading me to believe that the file is truly blank despite it obviously not being.
I have tried unregistered the service worker and updating manually.
SCRIPT ON INDEX
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw_basic.js')
.then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
SERVICE WORKER SCRIPT
var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
'./', './index.php',
'./profile.php',
'./support.php',
'./img/dance3-min.png',
'./css/agency',
'./css/agency.min.css',
'./css/eventform.css',
'./css/loginmodal.css',
'./css/profile.css',
'./css/support.css',
'./css/table.css',
'./css/timer.css'
]
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened Cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event)) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
if (response) {
console.log('Successfully fetched resource from chache: ${event.request.url}');
return response;
} else {
console.error('Failed to fetch resource: ${event.request.url}');
}
return fetch(event.request);
}
)
)
}
EDIT* I have gotten it to update by changing the name of the js file and manually unregistering the service worker in chrome however it doesn't always update this way sometimes requiring several attempts
I still feel like there must be a better way for doing this and in all the tutorials / documentation it seems like it should install the new one and activate once all tabs are unloaded but its not even installing the updated one at all.
EDIT*
I noticed the service worker tries to install and then disappears.
Example- Service worker #12 is active and running. I refresh and then for a second service worker #24 is installing and then suddenly its gone. At this point i really don't know whats going on other feeds are saying its a problem with the cache max age but I have it set to 0 in the htaccess
Cache-Control: max-age= 0
EDIT*
I have tried taking the service worker onto a different page remove the caching and just try to get it to update.
Currently my index looks like
<html>
<head>
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/beta/sw.js', {scope: '/beta/'})
.then(function(reg) {
// registration worked
console.log('Registration succeeded. Scope is ' + reg.scope);
}).catch(function(error) {
// registration failed
console.log('Registration failed with ' + error);
});
}
</script>
</head>
online page v2.0
</html>
and the service worker looks like
self.addEventListener('install', function(event) {
console.log("SW installed");
});
self.addEventListener('activate', function(event) {
console.log("SW activated");
});
self.addEventListener('fetch', function(event) {
console.log("Hijacked Signal");
event.respondWith(new Response("offline page"));
});
This Works when the user refreshes after visiting the page the text changes from online to offline. The problem occurs when i change the desired text (eg to offline 2.0). Anyone who has already visited the website is running the old service worker and so will see offline and not offline 2.0
a link to the page if anyone wishes to see whats going on
https://pakcollegelive.tk/beta/index.php
It turns out Cloudflare wasn't playing nice with the service worker files for whatever reason. It wasn't imperative that Cloudflare was used in my case so disabling it fixed the problem.

How to add service worker in Magento 2?

I had written service worker in JS but i am not getting where to add that file in Magento 2 PWA I had use tigren extension for achieving PWA but service worker is not working in that so I had written sevice worker of my own.
This is my service worker
//This is the "Offline page" service worker
//Install stage sets up the offline page in the cache and opens a new cache
self.addEventListener('install', function(event) {
var offlinePage = new Request('offline.html');
event.waitUntil(
fetch(offlinePage).then(function(response) {
return caches.open('pwabuilder-offline').then(function(cache) {
console.log('[PWA Builder] Cached offline page during Install'+ response.url);
return cache.put(offlinePage, response);
});
}));
});
//If any fetch fails, it will show the offline page.
//Maybe this should be limited to HTML documents?
self.addEventListener('fetch', function(event) {
event.respondWith(
fetch(event.request).catch(function(error) {
console.error( '[PWA Builder] Network request Failed. Serving offline page ' + error );
return caches.open('pwabuilder-offline').then(function(cache) {
return cache.match('offline.html');
});
}
));
});
//This is a event that can be fired from your page to tell the SW to update the offline page
self.addEventListener('refreshOffline', function(response) {
return caches.open('pwabuilder-offline').then(function(cache) {
console.log('[PWA Builder] Offline page updated from refreshOffline event: '+ response.url);
return cache.put(offlinePage, response);
});
});
This is service worker register js.
//This is the "Offline page" service worker
//Add this below content to your HTML page, or add the js file to your page at the very top to register service worker
if (navigator.serviceWorker.controller) {
console.log('[PWA Builder] active service worker found, no need to register')
} else {
//Register the ServiceWorker
navigator.serviceWorker.register('pwabuider-sw.js', {
scope: './'
}).then(function(reg) {
console.log('Service worker has been registered for scope:'+ reg.scope);
});
}
please help me out how to add service worker in magneto 2.

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.

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

Service worker throwing an net::ERR_FILE_EXISTS error?

service-worker.js:1 GET http://localhost:8080/service-worker.js net::ERR_FILE_EXISTS
This is the error I get every time I refresh after registering a service worker. I've made sure that the service-worker.js file exists in the root directory. Also the service worker is registered and working fine. But I still keep getting this error. Also I'm working on localhost.
This is my service-worker.js file:
console.log("SW startup");
var CACHE_NAME = "my_cache";
var urlsToCache = [
'./',
'./css/style.css',
'./js/script.js'
];
self.addEventListener('install', function(event) {
// Perform install steps
event.waitUntil(
caches.open(CACHE_NAME)
.then(function(cache) {
console.log('Opened cache');
return cache.addAll(urlsToCache);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(CACHE_NAME).then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request.clone()).then(function(response) {
console.dir(response);
console.log('hi');
cache.put(event.request.clone(), response.clone());
return response;
});
});
})
);
});
script.js file:
if (navigator.serviceWorker) {
console.log("ServiceWorkers are supported");
navigator.serviceWorker.register('service-worker.js')
.then(function(reg) {
console.log("ServiceWorker registered ◕‿◕");
console.dir(reg);
})
.catch(function(error) {
console.log("Failed to register ServiceWorker ಠ_ಠ");
console.dir(error);
});
}
I'm seeing the same issue. It can safely be ignored.
This bug tracks removing the noise from Chrome: https://code.google.com/p/chromium/issues/detail?id=541797
It should be live starting with Chrome 50.
From thread:
Improve error code for service worker bailing due to no update found
ServiceWorkerWriteToCacheJob is the URLRequestJob responsible for
fetching and writing the updated script. It fails with network error
when it wants to abort the update because the new script is the same
as the old one.
Currently that results in ERR_FAILED errors appearing in the DevTools
console and netlog, which is confusing and hard to debug because that
error also occurs for actual network errors. This patch changes the
error to FILE_EXISTS, so it's more clear why the job "failed".

Categories

Resources