The simplest service worker for a Web App Manifest

8k Views Asked by At

I must confess that I have no idea what a service worker is (TL;DR), but after reading around in the internet and SO, it seems that to have a Web App Manifest properly working, you need one.

Do I really need this extra script (service worker) to have the homescreen option on Android with Web App Manifest?

This is my /manifest.webmanifest:

{
  "short_name": "autocustos",
  "name": "Calculadora dos Custos do Automóvel",
  "icons": [
    {
      "src": "/favicon32x32.png",
      "type": "image/png",
      "sizes": "32x32"
    },
    {
      "src": "/favicon72x72.png",
      "type": "image/png",
      "sizes": "72x72"
    },
    {
      "src": "/favicon114x114.png",
      "type": "image/png",
      "sizes": "114x114"
    },
    {
      "src": "/favicon144x144.png",
      "type": "image/png",
      "sizes": "144x144"
    },
    {
      "src": "/favicon192x192.png",
      "type": "image/png",
      "sizes": "192x192"
    }
  ],
  "start_url": "/PT",
  "scope": "/",
  "background_color": "#F4F6FE",
  "display": "fullscreen",
  "theme_color": "#F4F6FE"
}

I have this in the head section

<link rel="manifest" href="/manifest.webmanifest" crossorigin="use-credentials">

And to serve my /manifest.webmanifest I set the content header to application/manifest+json

But Google Dev Tools on Application -> Manifest, tells me: enter image description here

2

There are 2 best solutions below

0
João Pimentel Ferreira On BEST ANSWER

Following the instruction on the comments I did the following:

Add a very simple /serviceWorker.js file at the url root, like this:

self.addEventListener("fetch", function(event) {
  console.log(`start server worker`)
});

Load the following piece of code either by embedding it on html head tag or loading it within a JS file after the event onload is triggered

if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('./serviceWorker.js')
    .then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }).catch(function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
}

Then the manifest.json as stated in the original post will work as expected

Based on this example: https://github.com/januwA/web-app-manifest

2
NinaW On

To get clarity about how all this fits together, head to https://developer.mozilla.org/en-US/docs/Web/Progressive_web_apps