VAN
DEL
.IO

PWA on a WordPress site

I will explain how to enable PWA on your wordpress site / blog.

It’s pretty easy, no plugins needed.

We need to create 2 files, if they dont already exist.
And then we need to add some javascript code to the site.

The two files we create are as follows:

sw.js : service worker file – which states which resources should be included and handles the cache fetch, install and activation on the clients device.


var cacheName = 'vandel.io';
var filesToCache = [
    '/',
    'https://path_to_themme/_styles.css'
];
self.addEventListener('install', function(e) {
    console.log('[ServiceWorker] Install');
    e.waitUntil(
        caches.open(cacheName).then(function(cache) {
            console.log('[ServiceWorker] Caching app shell');
            return cache.addAll(filesToCache);
        })
    );
});
self.addEventListener('activate', event => {
    event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', event => {
    event.respondWith(
        caches.match(event.request, { ignoreSearch: true }).then(response => {
            return response || fetch(event.request);
        })
    );
});

Manifest.json : a json data file containing the info about the cache content and image details


{
    "name": "Vandel.io",
    "short_name": "vandelio",
    "theme_color": "#333333",
    "background_color": "#d79f2a",
    "display": "standalone",
    "orientation": "portrait",
    "Scope": "/",
    "start_url": "https://vandel.io/",
    "icons": [{
            "src": "https://path_to_themeimages/icons/icon-72x72.png",
            "sizes": "72x72",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-96x96.png",
            "sizes": "96x96",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-128x128.png",
            "sizes": "128x128",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-144x144.png",
            "sizes": "144x144",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-152x152.png",
            "sizes": "152x152",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-192x192.png",
            "sizes": "192x192",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-384x384.png",
            "sizes": "384x384",
            "type": "image/png"
        },
        {
            "src": "https://path_to_themeimages/icons/icon-512x512.png",
            "sizes": "512x512",
            "type": "image/png"
        }
    ],
    "splash_pages": null
}

Since the cache content is theme specific regarding images and styling resources, the ideal place to put them is in the specific theme folder and the change the url’s in the code so it matches.

Javascript – place the js code in the footer or in a script loaded in the footer,


	function checkSwPm(){
		if (!('PushManager' in window)) {
			throw new Error('No Push API Support!')
		}else{
			console.log('PushManager API Support!')
		}
	}
	const registerServiceWorker = async () => {
		const swRegistration = await navigator.serviceWorker.register('/sw.js'); //notice the file name
		return swRegistration;
	}
	const requestNotificationPermission = async () => {
		const permission = await window.Notification.requestPermission();
		// value of permission can be 'granted', 'default', 'denied'
		// granted: user has accepted the request
		// default: user has dismissed the notification permission popup by clicking on x
		// denied: user has denied the request.
		if(permission !== 'granted'){
			throw new Error('Permission not granted for Notification');
		}
	}
	const main = async () => {
		checkSwPm();
		const swRegistration = await registerServiceWorker();
		//sconst permission =  await requestNotificationPermission();
	}
	main();
	
	self.addEventListener('activate', function(event) {
		event.waitUntil(
			caches.keys().then(function(cacheNames) {
			return Promise.all(
				cacheNames.filter(function(cacheName) {
				// Return true if you want to remove this cache,
				// but remember that caches are shared across
				// the whole origin
				}).map(function(cacheName) {
				return caches.delete(cacheName);
				})
			);
			})
		);
	});