Hi. Is there an example to create a service worker using Kotlin/JS.
How can I integrate coroutine with service worker?
Thank
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 => Navigator - Kotlin Programming Language
I hope that would help
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())
});