Skip to content

Instantly share code, notes, and snippets.

@XaviTorello
Last active June 8, 2017 11:43
Show Gist options
  • Save XaviTorello/ee612e6eaa53fd9708a2957087325e64 to your computer and use it in GitHub Desktop.
Save XaviTorello/ee612e6eaa53fd9708a2957087325e64 to your computer and use it in GitHub Desktop.
Intro a Service Workers

Registre

const SW_handler = 'sw.js';

const SW_params = {
  scope: '/', //o /gis o el root path que vulguis atacar
}

// Confirma que el browser suporti SWs
if ('serviceWorker' in navigator) {
 navigator.serviceWorker.register(SW_handler)
 .then(function(register_result) {
   // Registre OK!
   console.log('Registre fet, gogogo!');
   
 }).catch(function(err) {
   // Error registrant SW
   console.log('Error registrant SW, error: :', error);
 });
}

Instal·lació

Contingut de <SW_handler>

const urls_a_catxejar = [
  '/',
  '/capes',
  '/estils',
  '/script',
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open("cache_v1")
      .then(function(cache) {
        // Obre la catxe i catxeja les URIs definides
        return cache.addAll(urlsToCache);
      })
  );
});

Intercepció

Extén <SW_handler>

self.addEventListener('fetch', (event) => {
    console.log("Capturant", event.request.url);
    
    //Revisa si la request feta ha estat catxejada, sinó permet el fetch del recurs
    event.respondWith(
        caches.match(event.request).then(function(response) {
            return response || fetch(event.request);
        })
    );
});

Captura de pushos

Extén <SW_handler>

self.addEventListener('push', (event) => {
    console.log("Un push!", event);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment