clients-get-worker.js (1480B)
1 // This worker is designed to expose information about clients that is only available from Service Worker contexts. 2 // 3 // In the case of the `onfetch` handler, it provides the `clientId` property of 4 // the `event` object. In the case of the `onmessage` handler, it provides the 5 // Client instance attributes of the requested clients. 6 self.onfetch = function(e) { 7 if (/\/clientId$/.test(e.request.url)) { 8 e.respondWith(new Response(e.clientId)); 9 return; 10 } 11 }; 12 13 self.onmessage = function(e) { 14 var client_ids = e.data.clientIds; 15 var message = []; 16 17 e.waitUntil(Promise.all( 18 client_ids.map(function(client_id) { 19 return self.clients.get(client_id); 20 })) 21 .then(function(clients) { 22 // No matching client for a given id or a matched client is off-origin 23 // from the service worker. 24 if (clients.length == 1 && clients[0] == undefined) { 25 e.source.postMessage(clients[0]); 26 } else { 27 clients.forEach(function(client) { 28 if (client instanceof Client) { 29 message.push([client.visibilityState, 30 client.focused, 31 client.url, 32 client.type, 33 client.frameType]); 34 } else { 35 message.push(client); 36 } 37 }); 38 e.source.postMessage(message); 39 } 40 })); 41 };