An explanation of Progressive Web Apps for the non-PWA crowd

An explanation of Progressive Web Apps for the non-PWA crowd

<strong>Originally published by&nbsp;</strong><a href="https://medium.freecodecamp.org/@tomerpacific" target="_blank">tomerpacific</a> <em>at&nbsp;</em><a href="https://medium.freecodecamp.org/an-explanation-of-progressive-web-apps-for-the-non-pwa-crowd-8a400e275ea1" target="_blank">medium.freecodecamp.org</a>

The world of applications was classified into two categories not too long ago. You were either creating an application for Android devices or for iOS. Enter PWAs, or elongated, Progressive Web Applications. You have probably been hearing all about them for the past couple of years, but besides a nice acronym, you have no idea what a PWA is. As their popularity increases, it might be a good idea to get to know what all the fuss is about.

In this article, I’ll take you on a tour of what a PWA is, what components it is built from, and show you how you can make one on your own.

The Basics

A progressive web application is a website turned into an application. What this means is, that instead of having to code either in Java or Objective-C (or more recent mobile coding languages), you can write the code for the application, like you would for a website. You have your html files, your stylesheets, and your scripts.

Why would you build a PWA instead of a native application? For starters, imagine that once you release a PWA, you can change it constantly without having to republish your application. Since all the code is hosted on a server and not part of the APK/IPA, any change you make happens in real time.

If you have ever used an application that relies on a network connection, you are familiar with the frustration of not being able to do anything. With PWAs, you have the ability to offer an offline experience to your users in case of network issues.

And to add the cherry on top, there is an ability to prompt the user to add your PWA to their home screen. Something that native applications do not possess.

Components

There is a standard regarding a PWA, and you must adhere to it if you want to publish one. Each PWA is built from the following components:

  • A web app manifest
  • A service worker
  • Install experience
  • HTTPS
  • Creating an APK
  • Lighthouse audit

    The Manifest

This is purely a configuration file (.JSON), enabling you to change various settings of your PWA and how it will appear to the user. Below is an example of one:

{
      "name": "My PWA",
      "short_name": "PWA",
      "icons": [{
        "src": "your_icon.png",
          "sizes": "128x128",
          "type": "image/png"
        }],
      "start_url": "/index.html",
      "display": "standalone",
      "background_color": "#3E4EB8",
      "theme_color": "#2F3BA2"
    }

You must set either a name/short name key. When setting both, short name will be used on the home screen and the launcher. The name value will be used in the Add to Home Screen experience (or, application install prompt).

Display can have four different values:

  • fullscreen- this allows your application to take up the whole screen when it is opened
  • standalone- your application looks like a native application, hiding browser elements
  • minimal-ui - provides some browsing controls (only supported for Chrome mobile)
  • browser- like the name says your application’s look will be identical to a browsing experience

You can also set the *orientation *of your application and the *scope *of the pages considered to be within your application.

Don’t forget to add the manifest to your main html file by putting the following meta tag inside of your head tag:

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

The Service Worker

A service worker is a component running in the background of your website on the browser. It has a wide set of functionalities including, push notifications, caching assets and providing them for an offline experience and the ability to defer actions until the user has a stable connection to the internet. A service worker can be a whole Medium article on its own, so I won’t delve into the inner details of how it works. But, I will supply a vanilla example of one for you to use in your PWA.

It is customary to save the code related to the service worker in a file called sw.js.

✋ The location of the service worker is important since it can only access files that are in the same directory or subdirectory as itself. A service worker has a lifecycle that can be summed up to the following phases:

  • Registration
  • Installation/Activation
  • Responding to various events
//Inside your main html file (index.html), paste the following inside script tags at the end of your body tag
    //Registering a service worker
    if('serviceWorker' in navigator) {
      navigator.serviceWorker
               .register('/sw.js')
               .then(function() { console.log("Service Worker Registered"); });
    }


    --------------------------------


    //Inside your sw.js
    //You can get the polyfill from here: https://github.com/dominiccooney/cache-polyfill/blob/master/index.js
    importScripts('/serviceworker-cache-polyfill.js');


    //Listening in on an install event and caching site assets
    self.addEventListener('install', function(e) {
     e.waitUntil(
       caches.open('your_app_name').then(function(cache) {
         return cache.addAll([
           '/',
           '/index.html',
            // Place more assets
         ]);
       })
     );
    });


    //Listening in on fetch requests and if found in cache, bring file from cache
    self.addEventListener('fetch', function(event) {
     event.respondWith(
       caches.match(event.request).then(function(response) {
         return response || fetch(event.request);
       })
     );
    });

Pay attention to the comments to understand where to place the different lines of code

Install Experience

One of the unique features of a PWA is its install experience. What this translates to is prompting the user to install your application. To allow us to present this ability to the user, we will need to listen in on an event called beforeinstallprompt.* *Below is a code sample demonstrating the flow from presenting the user with the option to add the application to activating logic based on their choice.

var savedPrompt = null;


    window.addEventListener('beforeinstallprompt', beforeInstallPrompt);


    function beforeInstallPrompt(event) {
       event.preventDefault();
       savedPrompt = event;
       //implement logic to show your UI for adding your application to the home screen (probably a button)
    }


    //Call this method when the user has clicked the button in your UI
    function userClickedAddToHome() {
       savedPrompt.prompt();

       savedPrompt.userChoice
        .then(function(choiceResult){
      if (choiceResult.outcome === 'accepted') {
        //User has agreed to add application to Home screen
      } else {
        //User has declined to add application to Home screen
      }
      savedPrompt = null;
    });
    }

HTTPS

Not too long ago, websites could still use the all too common http protocol. Due to recent changes in security and in Chrome, all websites that do not operate under the https protocol will be marked as not secured. Even if your website does not handle user data or sensitive communication, it is still good practice to switch over to https.

And like I mentioned earlier, if you want to be able to release a PWA, it has to use the https protocol. If you don’t want to get into the hassle of acquiring a domain, finding a proper host for it and then enabling SSL, you can go for the easy option of Github. If you have an account, you can open a repository and set up a GitHub Page. This process is fairly simple and straightforward and the bonus is getting the HTTPS built in as part of Github.

Creating An APK

In order for our PWA to be available inside the Google Play Store, we need to create an APK. You can use the popular tool, PWA2APK, which will do the hard work for you. But if you prefer to learn how to do it yourself, keep reading.

Google has introduced a new way to integrate your PWA into the Play store using what is called a Trusted Web Activity, or TWA. With just a few simple steps you will learn how to create a TWA, which you can then upload to the Play store.

  1. Open Android Studio and create an empty activity
  2. Go to the project’s build.gradle file and add the jitpack repository
allprojects {
       repositories {
           google()
           jcenter()
           maven { url "https://jitpack.io" } // <---
       }
    }
  1. Go to the module level build.gradle file and add the following lines to enable Java8 compatibility
android {
        compileSdkVersion 28
        defaultConfig {
            applicationId "your_application_id"
            minSdkVersion 16
            targetSdkVersion 28
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
            }
        }

        //Add the lines below
        compileOptions {
            sourceCompatibility JavaVersion.VERSION_1_8
            targetCompatibility JavaVersion.VERSION_1_8
        }
    }
  1. Add the TWA support library as a dependency
dependencies {
       implementation 'com.github.GoogleChrome.custom-tabs-client:customtabs:d08e93fce3'
    }
  1. Add the activity XML inside your AndroidManifest file between the application tags
<activity
                android:name="android.support.customtabs.trusted.LauncherActivity">
               <meta-data
                   android:name="android.support.customtabs.trusted.DEFAULT_URL"
                   android:value="enter the url of your PWA" />
               <intent-filter>
                   <action android:name="android.intent.action.MAIN" />
                   <category android:name="android.intent.category.LAUNCHER" />
               </intent-filter>


               <intent-filter>
                   <action android:name="android.intent.action.VIEW"/>
                   <category android:name="android.intent.category.DEFAULT" />
                   <category android:name="android.intent.category.BROWSABLE"/>

                   <data
                     android:scheme="https"
                     android:host="enter your PWA url"/>
               </intent-filter>
            </activity>

Replace the android:value and android:host with your URL

  1. We need to create an association from the application to the website using a digital assets link. Paste the following inside your strings.xml file
<resources>


    <string name="asset_statements">
            [{
                \"relation\": [\"delegate_permission/common.handle_all_urls\"],
                \"target\": {
                    \"namespace\": \"web\",
                    \"site\": \"https://your PWA url\"}
            }]
        </string>

    </resources>
  1. Add the next meta tag as a child to your application tag inside the AndroidManifest.xml
<application>
      <meta-data
                android:name="asset_statements"
                android:resource="@string/asset_statements" />
      <activity>...</activity>
    </application>
  1. Create an upload key and keystore

  2. Use the following command to extract the SHA-256

keytool -list -v -keystore keystore_path -alias keystore_alias -storepass keystore_password -keypass key_password

Remember the details you entered when generating a keystore and your upload key

  1. Go to the assets link generator, supply the SHA-256 fingerprint, the package of your application and the web site's domain

  2. Place the result in a file named assetlinks.json under the location* /.well-known* in your website’s directory. Chrome will look for this destination specifically.

12. Generate a signed APK and upload to the Play store

Lighthouse

By now, I am sure you have already lost track of what is required from your PWA so it will be valid for publishing. There are so many things to take into consideration, that it is easy to lose track of what the requirements are.

Luckily for us, Google has created Lighthouse. It can be found in the Chrome Developer Tools (from Chrome version 60). It can be accessed easily by right-clicking inside the browser and selecting inspect. When the new pane opens, you will see an Audits tab at the far right corner.

The Audits Tab

Leaving the settings in this tab as they are, you can now run an audit by clicking on the “Run audits” button. This will take a minute or two, but by the end of it, you will receive an informative, graphical presentation of where your PWA ranks in respect to three properties:

  • Performance
  • Accessibility
  • Best Practices

Each property has a breakdown of where your application passed the requirements and where it didn’t. This lets you see where you need to make adjustments and where you are meeting the standard. If you are interested, you can find a breakdown of the checklist here.

PWA it up

We are at our journey’s end and hopefully you are feeling better prepared to navigate the world of PWAs. This article was inspired by the process I went through when creating one recently. You can check it out below:

=========================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

web-development pwa

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Top PWA Development Companies 2020 – TopDevelopers.co

Find the best PWA App Developers, to choose from a well-researched list of top PWA development companies and help you to develop Progressive Web Apps for your business.

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.