Active your APP or website like a PWA

·

2 min read

PWA

A PWA is a hybrid application between web and mobile. Imagine that when accessing a website that you like a lot on your smartphone you receive a warning to add the website to your application homepage.

With the app now installed on your phone, you can have the same experience you had for the browser now with no information on screen other than the application, that is, the entire browser interface such as address bar, buttons, favorites, etc., are removed.

manifest

create manifest.json and put the link in head

{
    "theme_color": "#396EB1",
    "background_color": "#EEEEEE",
    "display": "fullscreen",
    "scope": "./",
    "start_url": "./index.php",
    "name": "<app name>",
    "short_name": "<app short name>",
    "description": "<app description>",
    "icons": [
        {
            "src": "./icon-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "./icon-256x256.png",
            "sizes": "256x256",
            "type": "image/png"
        },
        {
            "src": "./icon-384x384.png",
            "sizes": "384x384",
            "type": "image/png"
        },
        {
            "src": "./icon-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ]
}

service worker [sw.js]

create a event listener [sw.js]

;
// name to set cache
const CACHE_NAME = 'pwa_app_name',
  urlsToCache = [
    './',
    './index.php',
    './pwa.js',
    './images/logo.png',
    './images/favicon.png'
  ]

//durante la fase de instalación, generalmente se almacena en caché los activos estáticos
self.addEventListener('install', e => {
  e.waitUntil(
    caches.open(CACHE_NAME)
      .then(cache => {
        return cache.addAll(urlsToCache)
          .then(() => self.skipWaiting())
      })
      .catch(err => console.log('fail to register in cache', err))
  )
})

// install serviceworker, activate and search resorces to valid connection
self.addEventListener('activate', e => {
  const cacheWhitelist = [CACHE_NAME]

  e.waitUntil(
    caches.keys()
      .then(cacheNames => {
        return Promise.all(
          cacheNames.map(cacheName => {
            // existing in cache
            if (cacheWhitelist.indexOf(cacheName) === -1) {
              return caches.delete(cacheName)
            }
          })
        )
      })
      // serviceworker activate current cache 
      .then(() => self.clients.claim())
  )
})

//browser read a url
self.addEventListener('fetch', e => {
  //response object in cache and try to get url 
  e.respondWith(
    caches.match(e.request)
      .then(res => {
        if (res) {
          //read from cache
          return res
        }
        //get url
        return fetch(e.request)
      }).catch(err => console.log('fail to fetch resource', err))
  )
})

register pwa serviceworker [pwa.js]

create a code for [pwa.js]

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('sw.js')
    .then(reg => console.log('Registro de SW exitoso', reg))
    .catch(err => console.warn('Error al tratar de registrar el sw', err))
}

update head with manifest [index.php]

insert manifest.json into your app in home web page ou [index.html] or [index.php]

<head>

<link rel="manifest" href="./manifest.json">

</head>

insert service worker before end tag body

<script src="./pwa.js"></script>


</body>
</html>