Creating Service Worker

Hi. Is there an example to create a service worker using Kotlin/JS.

How can I integrate coroutine with service worker?

Thank

Hi,
looking at javascript examples of service workers you can find something like:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

Hopefully you have “window” and “navigator” already in place using Kotlin Js. You can take a look at => https://kotlinlang.org/api/latest/jvm/stdlib/org.w3c.dom/-navigator/

I hope that would help

1 Like

Hi. Thanks for the reply. I’ve managed to modify the code to make it work.

The things I notice. adding service worker don’t work in window.onload {}. Must be put outside it.

The worker itself still must be written in javascript. Is it possible to write it using kotlin?

In count.js only ‘install’ event is called.

fun main() {
addServiceWorker()
window.onload = { … }
}

fun addServiceWorker() {
val navigator = window.navigator
console.log(“adding service worker ${navigator.serviceWorker}”)

window.addEventListener("load", EventListener {
    console.log("load event listener")

    navigator.serviceWorker.register("/count.js").then(
        onFulfilled = {
            console.log("ServiceWorker registration successful with scope: ", it.scope)
        }
        , onRejected = {
            console.log("ServiceWorker registration failed: ", it.message);
        }
    )
})

}

// count.js
function count1() {
var count = 0

setInterval(function () {
    console.log("counting " + count++)
}, 1000)

}

function count2() {
var count = 0

setInterval(function () {
    count = count+2
    console.log("counting " + count)
}, 1000)

}

self.addEventListener(‘install’, e => {
console.log(“sw install”)
console.log(count2())
});

self.addEventListener(‘activate’, event => {
console.log(“activate wait until …”)
event.waitUntil(self.clients.claim());
});

self.addEventListener(‘fetch’, event => {
console.log(“fetch event”)
console.log(count1())
});