common.js (2941B)
1 const url_base = "/document-policy/experimental-features/resources/"; 2 window.messageResponseCallback = null; 3 4 // Returns a promise which is resolved when the <iframe> is navigated to |url| 5 // and "load" handler has been called. 6 function loadUrlInIframe(iframe, url) { 7 return new Promise((resolve) => { 8 iframe.addEventListener("load", resolve); 9 iframe.src = url; 10 }); 11 } 12 13 // Posts |message| to |target| and resolves the promise with the response coming 14 // back from |target|. 15 function sendMessageAndGetResponse(target, message) { 16 return new Promise((resolve) => { 17 window.messageResponseCallback = resolve; 18 target.postMessage(message, "*"); 19 }); 20 } 21 22 23 function onMessage(e) { 24 if (window.messageResponseCallback) { 25 window.messageResponseCallback(e.data); 26 window.messageResponseCallback = null; 27 } 28 } 29 30 window.addEventListener("message", onMessage); 31 32 // Waits for |load_timeout| before resolving the promise. It will resolve the 33 // promise sooner if a message event with |e.data.id| of |id| is received. 34 // In such a case the response is the contents of the message |e.data.contents|. 35 // Otherwise, returns false (when timeout occurs). 36 function waitForMessageOrTimeout(t, id, load_timeout) { 37 return new Promise((resolve) => { 38 window.addEventListener( 39 "message", 40 (e) => { 41 if (!e.data || e.data.id !== id) 42 return; 43 resolve(e.data.contents); 44 } 45 ); 46 t.step_timeout(() => { resolve(false); }, load_timeout); 47 }); 48 } 49 50 function createIframe(container, attributes) { 51 var new_iframe = document.createElement("iframe"); 52 for (attr_name in attributes) 53 new_iframe.setAttribute(attr_name, attributes[attr_name]); 54 container.appendChild(new_iframe); 55 return new_iframe; 56 } 57 58 // Returns a promise which is resolved when |load| event is dispatched for |e|. 59 function wait_for_load(e) { 60 return new Promise((resolve) => { 61 e.addEventListener("load", resolve); 62 }); 63 } 64 65 setup(() => { 66 window.reporting_observer_instance = new ReportingObserver((reports, observer) => { 67 if (window.reporting_observer_callback) { 68 reports.forEach(window.reporting_observer_callback); 69 } 70 }, {types: ["document-policy-violation"]}); 71 window.reporting_observer_instance.observe(); 72 window.reporting_observer_callback = null; 73 }); 74 75 // Waits for a violation in |feature| and source file containing |file_name|. 76 function wait_for_violation_in_file(feature, file_name) { 77 return new Promise( (resolve) => { 78 assert_equals(null, window.reporting_observer_callback); 79 window.reporting_observer_callback = (report) => { 80 var feature_match = (feature === report.body.featureId); 81 var file_name_match = 82 !file_name || 83 (report.body.sourceFile.indexOf(file_name) !== -1); 84 if (feature_match && file_name_match) { 85 window.reporting_observer_callback = null; 86 resolve(report); 87 } 88 }; 89 }); 90 }