Konrad Dzwinel
navigator.serviceWorker.register('/worker.js') .then( swRegistration => console.log('Success 🎆') )
.catch( err => console.log('Failure 💩', err) );
<head>
…
<link rel="serviceworker" href="worker.js" />
…
</head>
const url = new URL("https://example.com/api/search?query='dfpl'");
if (url.hostname === 'example.com'
|| url.pathname.includes('/api/')
|| url.searchParams.has('query')) {
//...
}
fetch("https://example.com/data.json")
.then(response => {
if(response.ok) {
// ...
}
}) .catch(connectionFailed)
const request = new Request("https://example.com/endpoint", { method: "POST", headers: customHeaders, body: '{"conf":"dfpl"}'});
fetch(request).then(processResponse);
caches.open('cache-v1').then(cache => { cache.put(request, response); cache.add('/main.js'); cache.addAll(['/main.css', 'https://fonts.com/roboto.woff2']);
cache.match('/main.css').then(cachedResponse => {
if (cachedResponse) {
showResource(cachedResponse);
}
});
}).catch(err => console.error(err));
self.addEventListener('fetch', event => { const url = new URL(event.request.url);
if( url.pathname.startsWith('/article/') ) { event.respondWith( cache.match(event.request)
.then( cachedItem => {
if(cachedItem) return cachedItem;
return fetch(event.request)
.then( freshItem => { cache.put(event.request, freshItem.clone());
return freshItem; }); });
); }
});
navigator.serviceWorker.ready.then(swRegistration => {
swRegistration.sync.register('mySync');
});
self.addEventListener('sync', event => {
if (event.tag == 'mySync') {
event.waitUntil(doSomeStuff());
}
});
navigator.serviceWorker.register('/worker.js').then(swRegistration => { swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: publicKey
}).then( sub => console.log('endpoint:', sub.endpoint) );});
self.addEventListener('push', event => { event.waitUntil(
self.registration.showNotification('Title', {
body: 'The Message',
icon: 'images/icon.png',
tag: 'my-tag'
}));});