utils.js (1235B)
1 // Sends to Window |w| the object |{type, param}|. 2 function sendMessage(w, type, param) { 3 w.postMessage({"type": type, "param": param}, "*"); 4 } 5 6 // Returns a |Promise| that gets resolved with the event object when |target| 7 // receives an event of type |event_type|. 8 function getEvent(event_type, target) { 9 return new Promise(resolve => { 10 target.addEventListener(event_type, e => resolve(e), {once: true}); 11 }); 12 } 13 14 // Adds a listener that is automatically removed at the end of the test. 15 function addTestScopedListener(target, type, listener, test) { 16 target.addEventListener(type, listener); 17 test.add_cleanup(() => { 18 target.removeEventListener(type, listener); 19 }); 20 } 21 22 // Returns a |Promise| that gets resolved with |event.data| when |window| 23 // receives from |source| a "message" event whose |event.data.type| matches the string 24 // |message_data_type|. 25 function getMessageData(message_data_type, source) { 26 return new Promise(resolve => { 27 function waitAndRemove(e) { 28 if (e.source != source || !e.data || e.data.type != message_data_type) 29 return; 30 window.removeEventListener("message", waitAndRemove); 31 resolve(e.data); 32 } 33 window.addEventListener("message", waitAndRemove); 34 }); 35 }