partitioned-storage-sw.js (2423B)
1 // Holds the promise that the "resolve.fakehtml" call attempts to resolve. 2 // This is "the SW's promise" that other parts of the test refer to. 3 var promise; 4 // Stores the resolve funcution for the current promise. 5 var pending_resolve_func = null; 6 // Unique ID to determine which service worker is being used. 7 const ID = Math.random(); 8 9 function callAndResetResolve() { 10 var local_resolve = pending_resolve_func; 11 pending_resolve_func = null; 12 local_resolve(); 13 } 14 15 self.addEventListener('fetch', function(event) { 16 fetchEventHandler(event); 17 }) 18 19 self.addEventListener('message', (event) => { 20 event.waitUntil(async function() { 21 if(!event.data) 22 return; 23 24 if (event.data.type === "get-id") { 25 event.source.postMessage({ID: ID}); 26 } 27 else if(event.data.type === "get-match-all") { 28 clients.matchAll({includeUncontrolled: true}).then(clients_list => { 29 const url_list = clients_list.map(item => item.url); 30 event.source.postMessage({urls_list: url_list}); 31 }); 32 } 33 else if(event.data.type === "claim") { 34 await clients.claim(); 35 } 36 }()); 37 }); 38 39 async function fetchEventHandler(event){ 40 var request_url = new URL(event.request.url); 41 var url_search = request_url.search.substr(1); 42 request_url.search = ""; 43 if ( request_url.href.endsWith('waitUntilResolved.fakehtml') ) { 44 45 if (pending_resolve_func != null) { 46 // Respond with an error if there is already a pending promise 47 event.respondWith(Response.error()); 48 return; 49 } 50 51 // Create the new promise. 52 promise = new Promise(function(resolve) { 53 pending_resolve_func = resolve; 54 }); 55 event.waitUntil(promise); 56 57 event.respondWith(new Response(` 58 <html> 59 Promise created by ${url_search} 60 <script>self.parent.postMessage({ ID:${ID}, source: "${url_search}" 61 }, '*');</script> 62 </html> 63 `, {headers: {'Content-Type': 'text/html'}} 64 )); 65 66 } 67 else if ( request_url.href.endsWith('resolve.fakehtml') ) { 68 var has_pending = !!pending_resolve_func; 69 event.respondWith(new Response(` 70 <html> 71 Promise settled for ${url_search} 72 <script>self.parent.postMessage({ ID:${ID}, has_pending: ${has_pending}, 73 source: "${url_search}" }, '*');</script> 74 </html> 75 `, {headers: {'Content-Type': 'text/html'}})); 76 77 if (has_pending) { 78 callAndResetResolve(); 79 } 80 } 81 }