live-test-shim.js (2244B)
1 /* This Source Code Form is subject to the terms of the Mozilla Public 2 * License, v. 2.0. If a copy of the MPL was not distributed with this 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 4 5 "use strict"; 6 7 /* globals browser */ 8 9 if (!window.LiveTestShimPromise) { 10 const originalUrl = 11 "https://webcompat-addon-testbed.herokuapp.com/shims_test.js"; 12 13 const shimId = "LiveTestShim"; 14 15 const sendMessageToAddon = (function () { 16 const pendingMessages = new Map(); 17 const channel = new MessageChannel(); 18 channel.port1.onerror = console.error; 19 channel.port1.onmessage = event => { 20 const { messageId, response } = event.data; 21 const resolve = pendingMessages.get(messageId); 22 if (resolve) { 23 pendingMessages.delete(messageId); 24 resolve(response); 25 } 26 }; 27 function reconnect() { 28 const detail = { 29 pendingMessages: [...pendingMessages.values()], 30 port: channel.port2, 31 shimId, 32 }; 33 window.dispatchEvent(new CustomEvent("ShimConnects", { detail })); 34 } 35 window.addEventListener("ShimHelperReady", reconnect); 36 reconnect(); 37 return function (message) { 38 const messageId = 39 Math.random().toString(36).substring(2) + Date.now().toString(36); 40 return new Promise(resolve => { 41 const payload = { 42 message, 43 messageId, 44 shimId, 45 }; 46 pendingMessages.set(messageId, resolve); 47 channel.port1.postMessage(payload); 48 }); 49 }; 50 })(); 51 52 async function go(options) { 53 try { 54 const o = document.getElementById("shims"); 55 const cl = o.classList; 56 cl.remove("red"); 57 cl.add("green"); 58 o.innerText = JSON.stringify(options || ""); 59 } catch (_) {} 60 61 if (window !== top) { 62 return; 63 } 64 65 await sendMessageToAddon("optIn"); 66 67 const s = document.createElement("script"); 68 s.src = originalUrl; 69 document.head.appendChild(s); 70 } 71 72 window[`${shimId}Promise`] = sendMessageToAddon("getOptions").then( 73 options => { 74 if (document.readyState !== "loading") { 75 go(options); 76 } else { 77 window.addEventListener("DOMContentLoaded", () => { 78 go(options); 79 }); 80 } 81 } 82 ); 83 }