utils.js (2505B)
1 'use strict'; 2 3 let nextBackgroundFetchId = 0; 4 5 function loadScript(path) { 6 let script = document.createElement('script'); 7 let promise = new Promise(resolve => script.onload = resolve); 8 script.src = path; 9 script.async = false; 10 document.head.appendChild(script); 11 return promise; 12 } 13 14 // Waits for a single message received from a registered Service Worker. 15 async function getMessageFromServiceWorker() { 16 return new Promise(resolve => { 17 function listener(event) { 18 navigator.serviceWorker.removeEventListener('message', listener); 19 resolve(event.data); 20 } 21 22 navigator.serviceWorker.addEventListener('message', listener); 23 }); 24 } 25 26 // Registers the |name| instrumentation Service Worker located at "service_workers/" 27 // with a scope unique to the test page that's running, and waits for it to be 28 // activated. The Service Worker will be unregistered automatically. 29 // 30 // Depends on /service-workers/service-worker/resources/test-helpers.sub.js 31 async function registerAndActivateServiceWorker(test, name) { 32 const script = `service_workers/${name}`; 33 const scope = 'service_workers/scope' + location.pathname; 34 35 let serviceWorkerRegistration = 36 await service_worker_unregister_and_register(test, script, scope); 37 38 add_completion_callback(() => serviceWorkerRegistration.unregister()); 39 40 await wait_for_state(test, serviceWorkerRegistration.installing, 'activated'); 41 return serviceWorkerRegistration; 42 } 43 44 // Creates a Promise test for |func| given the |description|. The |func| will be 45 // executed with the `backgroundFetch` object of an activated Service Worker 46 // Registration. 47 // |workerName| is the name of the service worker file in the service_workers 48 // directory to register. 49 function backgroundFetchTest(func, description, workerName = 'sw.js') { 50 promise_test(async t => { 51 if (typeof test_driver === 'undefined') { 52 await loadScript('/resources/testdriver.js'); 53 await loadScript('/resources/testdriver-vendor.js'); 54 } 55 56 await test_driver.set_permission({name: 'background-fetch'}, 'granted'); 57 58 const serviceWorkerRegistration = 59 await registerAndActivateServiceWorker(t, workerName); 60 serviceWorkerRegistration.active.postMessage(null); 61 62 assert_equals(await getMessageFromServiceWorker(), 'ready'); 63 64 return func(t, serviceWorkerRegistration.backgroundFetch); 65 }, description); 66 } 67 68 // Returns a Background Fetch ID that's unique for the current page. 69 function uniqueId() { 70 return 'id' + nextBackgroundFetchId++; 71 }