Accessing myModule from Javascript

Hi, I’ve tried to access my kotlin kode from my service worker.

I’ve created a method in the root of my kotlin project:

fun workerRegistered() {
console.log(“service worker registered callback!”)
}

and then I try to call it from my service worker javascript:

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

but it said myModule is not defined. where should I look for the correct name? I’ve tried to look at the build.gradle.kts, settings, and project module.

Hi! Can you attach your project? Maybe this documentation helps you.

Hi thank you very much for responding. I already read the documentation, that’s how I get the myModule reference. But i don’t know why it doesn’t work.

The project is available at my github https://github.com/abangkis/Slowy

Hi!

You need to import file generated from kotlin inside your service worker using importScripts.
By default name of generated JS module is same as a name of gradle project, in your case likely it is “Slowy”.

Hi. Sorry, just been able to go back to this.

I’ve tried adding importScripts for slowy. But I got the error message

ServiceWorker registration failed: Failed to register a ServiceWorker for scope (‘http://localhost:8080/’) with script (‘http://localhost:8080/sw.js’): ServiceWorker script evaluation failed

erasing the importScripts I can install the service worker again, but back to the old problem. Can’t access the workerRegistered function

importScripts(‘Slowy.js’);

self.addEventListener(‘install’, event => {
console.log(‘v1 installing…’);
Slowy.workerRegistered()
});

self.addEventListener(‘activate’, event => {
console.log(‘v1 activated. Now ready to handle fetches!’);
// workerActivated()
});

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