Fetch in service worker

Trying to use window.fetch() from a service worker throws a ReferenceException saying that window is undefined.
The fetch() function itself is available within a service worker since it works when declared like so:

external fun fetch(input: dynamic, init: RequestInit = definedExternally): Promise = definedExternally

What is the rationale then for fetch() being defined as a function inside of window if window is not available in all contexts that fetch is available in?

Or is there a different way I should be calling fetch from within a service worker?

JS documentation says that there is a Window::fetch and there is a Worker::fetch. It seems to be that they have the same API, but I am not sure it is guaranteed. I think that part is just missing from kotlin stdlib wrapper for workers. It is a good idea to open a ticket about it.

Correction: Fetch API is defined on Window or worker: fetch - Kotlin Programming Language. So you can call it on worker.

There is the global self variable within ServiceWorker. To get access to self define external val self: ServiceWorkerGlobalScope and use self.fetch("/url"). Ctrl+click on fetch to see arguments. You will see RequestInit interface. There is a handy constructor-function org.w3c.fetch.RequestInit to create it. Just copy-paste it, if you don’t want to use @kotlin.internal.InlineOnly

Thank you both!

Now I declared
external val self: WindowOrWorkerGlobalScope
so that it works regardless if it’s running in widow or service worker, excellent! :slight_smile: