Enabling Service Workers on WordPress Without Plugins

Progressive web applications (PWAs) is the future of web application development. PWAs make use of the new Javascript APIs Provided by different browsers to implement native application like features on your web app. One such important API is the Service Worker API. It enables web developers to add many features like web push notifications and better cache control.

WordPress offers many plugins to use the service worker APIs but increasing the number of installed plugins can significantly affect the performance of your website. So in today’s article, I will walk you through the steps to manually create and register Javascript Service Workers on your WordPress website. Please ensure that your site has SSL encryption enabled and supports the HTTPs Protocol as browsers don’t allow unencrypted websites to register service workers. You can learn how to get an SSL Encryption Certificate for free using LetsEncrypt here.

What is a JavaScript Service Worker?

service workers

Javascript service workers are JavaScript files that run independently on the client’s browser and interacts with requests from your web server to achieve certain tasks like background data syncing or displaying push notifications. One disadvantage of the service worker is that since it runs on a separate thread, it has a very short life span.

Steps to Integrate a Service Worker to Your WordPress Application

1. Creating a Service Worker

The service worker is a simple JavaScript file that lives on your server. This file is served to the browser when requested and will run on a separate background thread on the browser. We shall create a simple Service Worker file that will enable us to push test notifications from the Google Chrome Dev Tools to ensure that the service worker has been registered.

It is recommended that you upload the Service Worker file to the root directory of your website. Create a new file “serviceworker.js”, add the following code to it and upload the file to your web server’s root directory so that it is accessible by calling “www.yourwebsite.com/serviceworker.js”.

function onPush(event) {
  var data = event.data.text();
  var target_url = "https://yourwebsite.com";
  event.waitUntil(
    self.registration.showNotification(data, {
      body: data,
      icon: null,
      tag: target_url,
      requireInteraction: true
    }));
}

self.addEventListener("push", onPush);

The above script will enable us to send test notifications to subscribed users on our website. It is recommended that you do not use this code in production as this code is just to show you how the service worker is expected to work.

2. Creating A JavaScript Functions File & Installing jQuery

We are going to create a JavaScript functions file which will contain the functions to register the service worker we created in the previous step on a web browser. We will also be installing jQuery which is required to run the code.

Open your theme editor from the Appearance > Editor menu. From the editor, open the footer.php file. This is where we will be including the functions required to register the serviceworker.js script.

Add the following lines right before the closing </body> tag.

<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>

<script src="/functions.js"></script>

Once that is done, we need to create a functions.js file in the root of your web application. So create a JavaScript file, name it functions.js and place it in the root directory of your web application and add the following code to the file.

function initiateSubscription(){
  Notification.requestPermission(function(permission){
    if (navigator && navigator.serviceWorker) {
      navigator.serviceWorker.getRegistrations().then(registrations => {
        if(!(registrations.length > 0)){
          registerServiceWorker();
        }
      });
    }   
  });
}

function registerServiceWorker() {
  return navigator.serviceWorker.register('/serviceworker.js').then(function(registration){
    subscribeToPushNotifications(registration);
  }).catch(function(e){
    console.log("ServiceWorker failed:", e);
  });
}

async function subscribeToPushNotifications(registration) {
  await navigator.serviceWorker.ready;
  registration.pushManager.subscribe({
    userVisibleOnly: true,
    applicationServerKey: new Uint8Array("ENTER YOUR APPLICATION SERVER PUBLIC KEY")}); 
}

In the above code, in the subscribeToPushNotifications(); function, you need to replace the “ENTER YOUR APPLICATION SERVER PUBLIC KEY” text with an actual application server public key. You can generate a key-pair from this link.

3. Calling the initiateSubscription(); Function to Register A Service Worker

Now to trigger the registration of the service worker, you can create a button to call the initiateSubscription(); function. Here is the code to do it

<button onclick="initiateSubscription();">Subscribe</button>

You are free to add the button anywhere on your website. Once it’s added, you’re ready to go. Open your website and click on the button you just created. You’ll be requested to grant notification permissions.

Under the ServiceWorkers section of the “Application” tab of chrome developer tools, you’ll see that your service worker has been registered. You can click on the Push button to test a sample notification on your website.

Integrating Service Workers with your WordPress website is as simple as that. You can modify your serviceworker.js to extend it’s functionality. I shall feature some options available through the service worker API in a future article. I’d recommend that you test the above steps on your local server before deploying it into production.

If you run into any problems during the process of setting up a service worker. Leave a comment below describing your issue and I will be more than happy to help you out. Stay tuned for more interesting articles.

Sreedev Kodichath

Sreedev Kodichath, a passionate software engineer, an avid blogger & an eloquent orator is the author of DevTechnica.

2 Responses

  1. Atif says:

    Hi Sreedev,

    Thanks for sharing a nice article.

    I am about to implement PWA into my site.

    I just want my website convert to PWA, i dont want push notification, actually i want a Home Screen option.

    Is it something you can help?

    Thanks in Advance.

    • Sreedev Kodichath says:

      Hey Atif,
      I apologize for the late reply.
      I hope you’ve found a solution. If you haven’t found it yet, drop me a mail at [email protected]
      I’ll be more than happy to help you out. Cheers! 🙂

Leave a Reply

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