session-storage-utils.js (2572B)
1 function getSessionStorageKeys() { 2 let keys = []; 3 let txt = ''; 4 for (let i = 0; i < sessionStorage.length; ++i) { 5 keys.push(sessionStorage.key(i)); 6 } 7 keys.sort(); 8 keys.forEach((key) => { 9 if (txt.length) { 10 txt += ', '; 11 } 12 txt += key; 13 }); 14 return txt; 15 } 16 17 function getNextMessage(channel) { 18 return new Promise(resolve => { 19 channel.addEventListener('message', e => { 20 resolve(e.data); 21 }, {once: true}); 22 }); 23 } 24 25 // session_storage_test() is a utility function for running session storage 26 // related tests that open a initiator page using window.open(). 27 function session_storage_test(testPath, uid) { 28 promise_test(async t => { 29 const testChannel = new PrerenderChannel('test-channel', uid); 30 t.add_cleanup(() => { 31 testChannel.close(); 32 }); 33 const gotMessage = getNextMessage(testChannel); 34 const url = 'resources/' + testPath + '?uid=' + uid; 35 window.open(url, '_blank', 'noopener'); 36 assert_equals(await gotMessage, 'Done'); 37 }, testPath); 38 } 39 40 // RunSessionStorageTest() is a utility function for running session storage 41 // related tests that requires coordinated code execution on both the initiator 42 // page and the prerendering page. The passed |func| function will be called 43 // with the following arguments: 44 // - isPrerendering: Whether the |func| is called in the prerendering page. 45 // - url: The URL of the prerendering page. |func| should call 46 // startPrerendering(url) when |isPrerendering| is false to start the 47 // prerendering. 48 // - channel: A PrerenderChannel which can be used to coordinate the code 49 // execution on the initiator page and the prerendering page. 50 // - done: A function that should be called when the test completes 51 // successfully. 52 async function RunSessionStorageTest(func, uid) { 53 const url = new URL(document.URL); 54 url.searchParams.set('prerendering', ''); 55 const params = new URLSearchParams(location.search); 56 // The main test page loads the initiator page, then the initiator page will 57 // prerender itself with the `prerendering` parameter. 58 const isPrerendering = params.has('prerendering'); 59 const prerenderChannel = new PrerenderChannel('prerender-channel', uid); 60 const testChannel = new PrerenderChannel('test-channel', uid); 61 window.addEventListener('pagehide', () => { 62 prerenderChannel.close(); 63 testChannel.close(); 64 }); 65 try { 66 await func(isPrerendering, url.toString(), prerenderChannel, () => { 67 testChannel.postMessage('Done'); 68 }) 69 } catch (e) { 70 testChannel.postMessage(e.toString()); 71 } 72 }