static-router-helpers.sub.js (2605B)
1 // Helper functions for ServiceWorker static routing API. 2 // 3 // test-helpers.sub.js must be loaded before using this. 4 5 // Get a dictionary of information recorded inside ServiceWorker. 6 // It includes: 7 // - request URL and mode. 8 // - errors. 9 // 10 // See: static-router-sw.js for details. 11 const get_info_from_worker = 12 async worker => { 13 const promise = new Promise(function(resolve) { 14 var channel = new MessageChannel(); 15 channel.port1.onmessage = function(msg) { resolve(msg); }; 16 worker.postMessage({port: channel.port2}, [channel.port2]); 17 }); 18 const message = await promise; 19 20 return message.data; 21 } 22 23 // Reset information stored inside ServiceWorker. 24 const reset_info_in_worker = 25 async worker => { 26 const promise = new Promise(function(resolve) { 27 var channel = new MessageChannel(); 28 channel.port1.onmessage = function(msg) { resolve(msg); }; 29 worker.postMessage({port: channel.port2, reset: true}, [channel.port2]); 30 }); 31 await promise; 32 } 33 34 // This script's directory name. It is used for specifying test files. 35 const scriptDir = document.currentScript.src.match(/.*\//)[0]; 36 37 // Register the ServiceWorker and wait until activated. 38 // {ruleKey} represents the key of routerRules defined in router-rules.js. 39 // {swScript} represents the service worker source URL. 40 // {swScope} represents the service worker resource scope. 41 const registerAndActivate = async (test, ruleKey, swScript, swScope) => { 42 if (!swScript) { 43 swScript = scriptDir + 'static-router-sw.js' 44 } 45 if (!swScope) { 46 swScope = scriptDir; 47 } 48 const swURL = `${swScript}?key=${ruleKey}`; 49 const reg = await service_worker_unregister_and_register( 50 test, swURL, swScope, { type: 'module' }); 51 add_completion_callback(() => reg.unregister()); 52 const worker = reg.installing; 53 await wait_for_state(test, worker, 'activated'); 54 55 return worker; 56 }; 57 58 // Create iframe with the given url. This automatically removes the iframe in a 59 // cleanup. 60 const createIframe = async (t, url) => { 61 const iframe = await with_iframe(url); 62 t.add_cleanup(() => iframe.remove()); 63 64 return iframe; 65 }; 66 67 // Register a service worker, then create an iframe at url. 68 function iframeTest(url, ruleKey, callback, name) { 69 return promise_test(async t => { 70 const worker = await registerAndActivate(t, ruleKey); 71 const iframe = await createIframe(t, url); 72 await callback(t, iframe.contentWindow, worker); 73 }, name); 74 }; 75 76 function randomString() { 77 let result = ""; 78 for (let i = 0; i < 5; i++) { 79 result += String.fromCharCode(97 + Math.floor(Math.random() * 26)); 80 } 81 return result; 82 }