How to add service worker in Magento 2? - javascript

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.

Related

router.navigate(url) not going through Service worker fetch event

Our platform is old angular (v4) and we use plain JavaScript file (sw.js) to register Service worker in index html page. I see install and activate are working fine. Just simple events [for testing]
self.addEventListener('install', function(event) {
event.waitUntil(self.skipWaiting()); // Activate worker immediately
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim()); // Become available to all pages
});
Then Angular component routes to our main page via router.navigate('pagename')
and browser even routes to that page, but service worker fetch event is not triggered..
self.addEventListener('fetch', event => event.respondWith(onFetch(event)));
Any idea how to fix this issue? Thank you.
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});

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?

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.

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