utils.js (2178B)
1 // Returns a Promise that gets resolved with `event.data` when `window` receives from `source` a 2 // "message" event whose `event.data.type` matches the string `message_data_type`. 3 function getMessageData(message_data_type, source) { 4 return new Promise(resolve => { 5 function waitAndRemove(e) { 6 if (e.source != source || !e.data || e.data.type != message_data_type) 7 return; 8 window.removeEventListener("message", waitAndRemove); 9 resolve(e.data); 10 } 11 window.addEventListener("message", waitAndRemove); 12 }); 13 } 14 15 // A helper that simulates user activation on the current frame if `activate` is true, then posts 16 // `message` to `frame` with the target `origin` and specified `capability` to delegate. This helper 17 // awaits and returns a Promise fulfilled with the result message sent in reply from `frame`. 18 // However, if the `postMessage` call fails, the helper returns a Promise rejected with the 19 // exception. 20 async function postCapabilityDelegationMessage(frame, message, origin, capability, activate) { 21 let result_promise = getMessageData("result", frame); 22 23 if (activate) 24 await test_driver.bless(); 25 26 let postMessageOptions = {targetOrigin: origin}; 27 if (capability) 28 postMessageOptions["delegate"] = capability; 29 try { 30 frame.postMessage(message, postMessageOptions); 31 } catch (exception) { 32 return Promise.reject(exception); 33 } 34 35 return await result_promise; 36 } 37 38 // Returns the name of a capability for which `postMessage` delegation is supported by the user 39 // agent, or undefined if no such capability is found. 40 async function findOneCapabilitySupportingDelegation() { 41 const capabilities = ["fullscreen", "payment", "display-capture"]; 42 43 for (let i = 0; i < capabilities.length; i++) { 44 try { 45 await postCapabilityDelegationMessage(window, "any_message", "/", capabilities[i], false); 46 assert_unreached(); 47 } catch (exception) { 48 if (exception.name != "NotSupportedError") 49 return capabilities[i]; 50 // Ignore all other exceptions to continue searching through the list. 51 } 52 }; 53 54 return undefined; 55 }