Reputation: 455
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);
}
Upvotes: 3
Views: 1567
Reputation: 56064
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.
Upvotes: 4