Creating a simple Progressive Web App (PWA) with .Net Core

Progressive web apps or PWAs can replace many native apps. Depending on your device, you can  cache content, take photos, detect photos, recognize speech, use geolocation services, and many other features of devices just using Html 5 and javascript.  The app, once created, can then be installed on any device without changing the code and without the need for the user to install the app from an app store, such as Google Play.  The What Web Can Do website  tells us which features are available on each device. Just open the What Web Can Do website on the device of interest to see your options for that device.

This post will give a simple example of creating a PWA with .Net Core. The example app converts Celsius to Fahrenheit and vice versa and will run offline once installed. It is more than a website. You don’t need to be online or to open a browser for the app to function.  Just click on the app icon on your home screen on your iphone, ipad, android device, or even your Win 10 computer. You can try the example app at the Today Data converter site.

WebEssentials.AspNetCore.PWA

The first step is to install the NuGet package WebEssentials.AspNetCore.PWA into your Microsoft Visual Studio Dependencies folder. This will take care of the heavy lifting. 

Modify your startup.cs

Next go to the file startup.cs and add lines to the ConfigureServices method. Notice that I set registering the service worker and registering the manifest to false.  This will be taken care in the view.

public void ConfigureServices(IServiceCollection services)
        {
            ...
            services.AddProgressiveWebApp(new WebEssentials.AspNetCore.Pwa.PwaOptions
            {
                RegisterServiceWorker = false,
                RegisterWebmanifest = false
            });
        }

Create the view

Next, you want to create the view that contains the works of your app. In the body of your view place this code

<h1>Temperature Converter </h1>
    <div id="converter">

        <label id="lblFahrenheit">F<sup>o</sup></label>
        <input id="inputFahrenheit" type="number" placeholder="Fahrenheit"
               oninput="temperatureConverter(this.value)"
               onchange="temperatureConverter(this.value)">


        <img src="~/images/arrows_vertical.gif" alt="arrows to separate Celsius from Fahrenheit" />



        <label id="lblCelsius">C<sup>o</sup></label>
        <input id="inputCelsius" type="number" placeholder="Celsius"
               oninput="temperatureConverter2(this.value)"
               onchange="temperatureConverter2(this.value)">

    </div>

You will need some kind of arrow gif. Feel free to use any image in the sample PWA.

Add the logic of the app

 Now add the javascript that makes the conversion work.

function temperatureConverter(valNum) {
            valNum = parseFloat(valNum);
            result = ((valNum - 32) / 1.8).toFixed(1);
            document.getElementById("inputCelsius").value = result;
        }

        function temperatureConverter2(valNum) {
            valNum = parseFloat(valNum);
            result = ((valNum * 1.8) + 32).toFixed(1);
            document.getElementById("inputFahrenheit").value = result;
        }

Add  Meta tags.

<title>Converts Fahrenheit to Celsius and Celsius to Fahrenheit</title>
    <link rel="manifest" href="/manifest-converter.json">
    <!-- icon in the highest resolution we need it for -->
    <link rel="icon" sizes="192x192" href="/images/fc-192x192.png">
 <link rel="icon" sizes="512x512" href="/images/fc-192x192.png">

    <!-- reuse same icon for Safari -->
    <link rel="apple-touch-icon" href="/images/fc-192x192.png">
 <link rel="apple-touch-icon" href="/images/fc-512x512.png">

Note that there are links to the icons for your app. You need special links to make the app run on IOS. Also, there is a link to the manifest for your site which I will show later in this post.

Add the Service Worker

Also, in the head you will need javascript to load the serviceworker. 

if ('serviceWorker' in navigator) {
           navigator.serviceWorker.register('/serviceworker', { scope: '/converter/' }).then(function (registration) {
                console.log('Service worker registration succeeded:', registration);
            }, /*catch*/ function (error) {
                console.log('Service worker registration failed:', error);
            });
        } else {
            console.log('Service workers are not supported.');
        }

Here we have restricted the serviceworker to just the scope “converter.” On my domain, the app installs at: todaydata.com/converter.

So, you see that I wanted the scope to just be “converter” and that is why I did not use the default in the start.cs file. Doing it this way allows you to create other apps using the same domain.

Add some style

To make it look better, add some style as follows:

<style>
        h1 {
            color: #1038cd;
            font-family: Cambria;
        }

        #converter {
            display: flex;
            flex-direction: column;
            justify-content: flex-start;
            align-items: flex-start;
            margin-left: 20px;
            margin-right: 20px;
        }

            #converter input {
                height: 40px;
                width: 150px;
                font-size: x-large;
                padding-left: 20px;
                padding-right: 20px;
            }

        img {
            padding: 10px;
            margin: 0px;
        }
    </style>

Here I made use of flexboxes for layout.

Add view to controller

Now we are finished with the view. Add this view to your controller.

Create the manifest

Finally, we add the manifest file which I have called manifest-converter.json. Put it in the root.

{
  "name": "Convert Temperatures: Fahrenheit to Celsius",
  "short_name": "temperature converter",
  "description": "Progressive web app for todaydata.com to convert temperatures",
  "icons": [
    {
      "src": "/images/fc-192x192.png",
      "sizes": "192x192"
    },
    {
      "src": "/images/fc-512x512.png",
      "sizes": "512x512"
    }
  ],
  "display": "standalone",
  "start_url": "/converter/"
}

You can actually add a manifest file to any web page. The service worker  is what makes the page a PWA. The PWA will cache the content and allow the app to work offline. However, a manifest is useful for any page that users might want to save to their home screen.

How to use the  PWA

Support for PWAs is not complete across all browsers, but is coming online soon. To use the PWA,  use a browser to navigate to the app and install the app as explained below. After it is installed, you can click on it from your home screen.

As of this writing, to install on iphone or ipad, open Safari and choose the options icon. Click the “Add to Home Screen” icon.   For android and Windows 10, use the Chrome browser and choose the options icon with three vertically spaced dots. Select the install option. With IOS or Android devices, you will find the result on your home screen. With Win 10, the app will be in the list of apps that you can reach with the Microsoft Start icon. 

A final note. You must secure your site with HTTPS for PWAs to work.

Leave a Reply

Your email address will not be published. Required fields are marked *