TechWordPressEasy and Simple Guide on Adding "Add to Home Screen" to support...

Easy and Simple Guide on Adding “Add to Home Screen” to support PWA

After Accelerated Mobile Pages (AMP) Google announced Progressive Web Apps (PWA) that let the website owners generate a signed APK and install on the users’ device within the fraction of seconds which has tons of possibilities to deploy-on.

In this tutorial, we would be learning to create the Progressive Web Apps (PWA) to HTML based or WordPress based website.

Requirements:

  1. HTTPS-enabled website
  2. manifest.json
  3. service-worker.js
  4. PNG icons etc

It should be noted that PWA is only supported with the HTTPS-secure website, which means it won’t work with the sites that are still using the insecure HTTP protocol. If you are site is not having the HTTPS support you can either install the SSL or join the most significant free content delivery network (CDN), Cloudflare that has inbuilt HTTPS (SSL) support and that’s of free of cost.

We would be following five steps towards adding and integrating the PWA and “add to home screen” option to your website.

Step 1– Generating PNG icons 

Generate the PNG images of your logo in the 192×192, 256×256, and 512×512 pixel sizes. Tons of websites offer free generation of icons and favicons in different sizes. I’ll recommend favicomatic.com and of course, you can always Google for more possibilities.

Step 2– Creating manifest.json file

The manifest.json the file is used to store the critical information and the instructions used by Chrome to generate the PWA.

Create an empty file named manifest.json in the root of your website and add the following code in it after making necessary changes.

Here is an example which you can change accordingly to make it yours:

{
  "name": "Isrg Knowledge Base",
  "short_name":"Isrg Lite",
  "description": "Isrg Rajan the official website that offers latest News, Education, Knowledgebase, Articles. Sci-Tech, Lifestyle, Health, Travels, Gadgets, IT Solution..",
  "icons": [
    {
      "src": "192x192.png",
      "type": "image/png",
      "sizes": "192x192"
    },
    {
      "src": "256x256.png",
      "type": "image/png",
      "sizes": "256x256"
    },
    {
      "src": "512x512.png",
      "type": "image/png",
      "sizes": "512x512"
    }
  ],
  "permissions":[
    "gcm",
    "storage",
    "notifications"
  ],
  "author": {
    "name":"Isrg",
    "wesbite":"https://www.isrgrajan.com/"
  },
  "gcm_sender_id": "YOUR-GCM_ID",
  "gcm_user_visible_only": true,
  "start_url": "/",
  "display": "standalone",
  "background_color":"#FFF",
  "theme_color": "#FFF",
  "orientation": "portrait"
}

Replace YOUR-GCM_ID with your Google Firebase Cloud Messaging ID and all other details as per your website.

Step 3– Creating service-worker.js

The service-worker.js is an important file that will handle various events and also it will show the “Add to home screen” pop up dialog, help in generating the web APK for your websites by fetching the details from your manifest.json file.

Create an empty file named service-worker.js in the root of your website and copy-paste the below code in it:

self.addEventListener('install', function(event) {
  console.log('[Service Worker] Installing Service Worker ...', event);
});
self.addEventListener('activate', function(event) {
 console.log('[Service Worker] Activating Service Worker ....', event);
});
self.addEventListener('fetch', function(event) {
  event.respondWith(
caches.match(event.request).then(function(response) {
  if (response) {
    return response;
  } else {
    return fetch(event.request).then(function(res) {
      return caches.open('dynamic').then(function(cache) {
        cache.put(event.request.url, res.clone());
        return res;
      });
    });
  }
})
  );
});

Deploying on custom or HTML based website

To implement the “Add to home screen” support and create PWA for your website, add the below code just before </head> tag:

<link rel="manifest" href="https://www.YOUR-WEBSITE.com/manifest.json"/>

Add the below code just before </body> tag ends:

<script>
    if ('serviceWorker' in navigator) {
      console.log("Will service worker register?");
      navigator.serviceWorker.register('https://www.YOUR-WEBSITE.com/service-worker.js').then(function(reg){
        console.log("Yes it did.");
      }).catch(function(err) {
        console.log("No it didn't. This happened: ", err)
      });
    }
  </script>

Adding PWA support to WordPress

There are two possible ways to add PWA support and “Add to Home screen” button on your website:

  1. Using Plugin.
  2. Adding the above code that we just learnt.

You can use the Super Progressive Web Apps WordPress plugin to add the PWA support on your WordPress or add the above codes manually.

Adding PWA and “Add to Home screen” feature to WordPress without Plugin

I’m assuming that you’ve already created the manifest.json and service-worker.js in the root of your website and added the above-suggested code after making changes as per your domain. If you’ve created these files, the only step left is adding the required HTML and JavaScript tags in your current template.

Open the current theme folder and in functions.php add the following code:

add_action( 'wp_footer', function () { ?>
?>
<script>
    if ('serviceWorker' in navigator) {
      console.log("Will service worker register?");
      navigator.serviceWorker.register('<?=get_site_url();?>/service-worker.js').then(function(reg){
        console.log("Yes it did.");
      }).catch(function(err) {
        console.log("No it didn't. This happened: ", err)
      });
    }
  </script>
<?php } );

Do not add the below code in functions.php if OneSignal plugin is installed, instead login into your WordPress admin dashboard choose OneSignal Push> Configuration> Custom manifest.json URL and change the URL to your manifest.json which you have created in the root of your domain.

function pwa_head_tag_inclusion() {
echo '<link rel="manifest" href="'.get_site_url().'/manifest.json">'; 
}
add_action( 'wp_head', 'pwa_head_tag_inclusion' );

Troubleshooting

Even after adding the codes manually is “add to home screen” pop-up dialog is not appearing? Well, you can try the following steps to resolve it:

  1. Clear the cache of your website if you are using Caching Plugins and also of your web browser.
  2. Ensure that manifest.json in <head> and above JavaScript tag is begin added.
  3. Cross-check the URLs in the manifest.json, service-worker.js, head and footer.
  4. Debug using Google Chrome.

IR Digital Media Team
IR Digital Media Teamhttps://www.isrgrajan.com/
IR Digital Media Team is a member of Digital Pradesh, a collective of journalists, reporters, writers, editors, lawyers, advocates, professors, and scholars affiliated with the Digital Pradesh.

Latest Updates