Is it possible to direclty read a variable from a service worker (ServiceWorkerGlobalScope)?

Viewed 585

Is it possible to get the counter variable (ServiceWorkerGlobalScope) from the main thread without using the postMessage method?

service-worker.js:

    let counter = 42;

    self.addEventListener("message", function (event: any) {
        let client = event.source;
        client.postMessage(counter);
    }
1 Answers

It's not possible to directly reference a variable from a different global scope.

You can use postMessage() to send values between the WindowGlobalScope and ServiceWorkerGlobalScope, as in your example.

You can also serialize variables to a shared storage that's accessible from both global scopes, like IndexedDB or the Cache Storage API. idb-keyval is an easy to use library that works in both scopes.

Related