webchannel.html (3198B)
1 <!DOCTYPE html> 2 <!-- This Source Code Form is subject to the terms of the Mozilla Public 3 - License, v. 2.0. If a copy of the MPL was not distributed with this 4 - file, You can obtain one at http://mozilla.org/MPL/2.0/. --> 5 <html> 6 <head> 7 <meta charset="utf-8"/> 8 <title></title> 9 </head> 10 <body> 11 <script> 12 "use strict"; 13 // This file is used to test opening the given script in devtools debugger 14 // from a front-end. 15 16 // The following are the titles used to communicate the page's state to the tests. 17 // Keep these in sync with any tests that read them. 18 const initialTitle = "Waiting to send the webchannel request"; 19 const successTitle = "Request sent"; 20 const errorTitle = "Error" 21 22 document.title = initialTitle; 23 24 // A function which requests the favicons from the browser using the 25 // OPEN_SCRIPT_IN_DEBUGGER WebChannel message. 26 function sendWebchannelRequest(requestBody) { 27 return new Promise((resolve, reject) => { 28 const requestId = 0; 29 30 function listener(event) { 31 window.removeEventListener( 32 "WebChannelMessageToContent", 33 listener, 34 true 35 ); 36 37 const { id, message } = event.detail; 38 39 if (id !== "profiler.firefox.com" || 40 !message || 41 typeof message !== "object" 42 ) { 43 console.error(message); 44 reject(new Error("A malformed WebChannel event was received.")); 45 return; 46 } 47 48 if (!message.type) { 49 console.error(message); 50 reject(new Error("The WebChannel event indicates an error.")); 51 return; 52 } 53 54 if (message.requestId === requestId) { 55 if (message.type === "SUCCESS_RESPONSE") { 56 resolve(message.response); 57 } else { 58 reject(new Error(message.error)); 59 } 60 } 61 } 62 63 window.addEventListener("WebChannelMessageToContent", listener, true); 64 65 window.dispatchEvent( 66 new CustomEvent("WebChannelMessageToChrome", { 67 detail: JSON.stringify({ 68 id: "profiler.firefox.com", 69 message: { type: "OPEN_SCRIPT_IN_DEBUGGER", requestId, ...requestBody}, 70 }), 71 }) 72 ); 73 }) 74 } 75 76 async function runTest() { 77 try { 78 // We get the request body from the mochitest itself by reading the 79 // url search params. 80 const params = new URLSearchParams(document.location.search); 81 const requestBody = JSON.parse(params.get("request")); 82 83 await sendWebchannelRequest(requestBody); 84 document.title = successTitle; 85 } catch (error) { 86 // Catch any error and notify the test. 87 document.title = errorTitle; 88 dump('An error was caught in webchannel.html\n'); 89 dump(`${error}\n`); 90 console.error( 91 "An error was caught in webchannel.html", 92 error 93 ); 94 } 95 } 96 97 runTest(); 98 </script> 99 </body> 100 </html>