Simple way to convert existing HTML web application to a PWA
Published: 2020-03-24 19:11:29

Hey everyone, this is my first post so wish me _luck_!

##TLDR;
You will have the template and files for converting your HTML page to a PWA like godspeed.

So we need the following files
1. `manifest.json`
2. `sw.js` (service worker)

An example of `manifest.json` can be found in the following [gist](https://gist.github.com/Rohithgilla12/e9345684a82b36045a34fb2675469ded).

This is how a `manifest.json` file looks like.
```json
{
  "name": "CoolApp",
  "short_name": "Cool",
  "theme_color": "#2196f3",
  "background_color": "#2196f3",
  "display": "standalone",
  "Scope": "/",
  "start_url": "/",
  "icons": [
    {
      "src": "assets/img/icons/icon-72x72.png",
      "sizes": "72x72",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-96x96.png",
      "sizes": "96x96",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-128x128.png",
      "sizes": "128x128",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-144x144.png",
      "sizes": "144x144",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-152x152.png",
      "sizes": "152x152",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-192x192.png",
      "sizes": "192x192",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-384x384.png",
      "sizes": "384x384",
      "type": "image/png"
    },
    {
      "src": "assets/img/icons/icon-512x512.png",
      "sizes": "512x512",
      "type": "image/png"
    }
  ],
  "splash_pages": null
}
```

Now, one of the most crucial options in `manifest.json` is `display`.
`standalone` gives us a proper UI when installed as a native application.
You can explore other options [here](https://superpwa.com/doc/web-app-manifest-display-modes/).

Now coming to generating `icons`. I strongly suggest [this](https://app-manifest.firebaseapp.com/) website, which works like a charm, it generates both `manifest.json` and `icons`.

Note: When uploading the image for generating icons, please make sure the size of the image you are uploading is **512 X 512**.

Now coming to our `sw.js` file.
```js
/*
 global workbox
*/

importScripts(
  "https://storage.googleapis.com/workbox-cdn/releases/4.3.1/workbox-sw.js"
);

if (workbox) {
  console.log(`Yay! Workbox is loaded 🎉`);
  workbox.routing.registerRoute(
    new RegExp(".*.js"),
    new workbox.strategies.NetworkFirst()
  );
  workbox.routing.registerRoute(
    /\.css$/,
    new workbox.strategies.StaleWhileRevalidate({ cacheName: "css-cache" })
  );

  workbox.routing.registerRoute(
    /\.(?:png|jpg|jpeg|svg|gif)$/,
    new workbox.strategies.CacheFirst({
      cacheName: "image-cache",
      plugins: [
        new workbox.expiration.Plugin({
          // Cache only 20 images.
          maxEntries: 20,
          // Cache for a maximum of a week.
          maxAgeSeconds: 7 * 24 * 60 * 60
        })
      ]
    })
  );
} else {
  console.log(`Boo! Workbox didn't load 😬`);
}
```
It uses [Google Workbox](https://developers.google.com/web/tools/workbox) for PWA support. It handles almost everything, we can sit back and relax.

Now there are a couple more steps until your website is a PWA.

We edit the `index.html` file.

* Add the following line in the `<head>` tag.
```html
<link rel="manifest" href="/manifest.json">
```
Which ensures `manifest.json` is linked.

* Now add the following script, to finish the process.
```js
<script>
		// 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

		// Check compatibility for the browser we're running this in
		if ("serviceWorker" in navigator) {
			if (navigator.serviceWorker.controller) {
				console.log("[PWA Builder] active service worker found, no need to register");
			} else {
				// Register the service worker
				navigator.serviceWorker
					.register("sw.js", {
						scope: "./"
					})
					.then(function (reg) {
						console.log("[PWA Builder] Service worker has been registered for scope: " + reg.scope);
					});
			}
		}
	</script>

```

Annnnnd Done. TADA!! when you open the application on an android phone or chrome browser in any desktop you should see an install button.

_**Bonus**_

To add notification support to Progressive Web Applications a.k.a PWA.
Just add the following snippet after registering the `Service Worker`.

```js
// To ask permission for notification.
Notification.requestPermission(function(status) {
  console.log("Notification permission status:", status);
});

// To send a notification
function displayNotification() {
  if (Notification.permission == "granted") {
    navigator.serviceWorker.getRegistration().then(function(reg) {
      reg.showNotification("Thanks for subscribing for to our notifications.");
    });
  }
}

```

You can call the `displayNotification` function, it sends the notification to the users.

P.S: In this article, I didn't explain what each line of the code does, it's a *TL;DR* article to make an existing web site a Progressive Web Application. 

Thanks, hope you liked it.