How can I get the WindowClient id of the current window?

25 Views Asked by At

From inside a service worker, I can do await clients.matchAll({includeUncontrolled: true}) to get a list of the current windows that the service worker can control and communicate with. For example, when I do that and I have 2 windows opened, I get an array with 2 WindowClient objects that looks something like this:

WindowClient {visibilityState: 'visible', focused: true, url: 'http://localhost:3000/', id: 'f56e10ac-6a7c-44ca-8322-11165a45eb4b', type: 'window'}
WindowClient {visibilityState: 'hidden', focused: false, url: 'http://localhost:3000/', id: 'b1be5170-8e98-4927-a53b-48c4752a82f1', type: 'window'}

It is noteworthy that each window has an id there. Now, my question is, from code that runs inside a window, is it possible to somehow get hold of that id?

1

There are 1 best solutions below

2
guest271314 On BEST ANSWER

With complicity of the ServiceWorker, and the Client or WindowClient, yes.

You can get the fetchEvent.resultingClientId in fetch handler and communicate that ID to the client in the headers, using postMessage(), or other means.