bug1287715-littlealchemy2.com-fix-audio-race-condition.js (1826B)
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 /** 8 * Bugs 1287715 - Audio intermittently does not work. 9 * 10 * The site relies on unspecified behavior in Chromium and WebKit where 11 * they will defer firing loadedmetadata events until after a listener 12 * for the event is attached. We can mimic that behavior here. 13 */ 14 15 /* globals exportFunction */ 16 17 console.info( 18 "loadedmetadata event is being deferred until GAME_READY. See https://bugzilla.mozilla.org/show_bug.cgi?id=1287715 for details." 19 ); 20 21 let loadedmetadataEvent; 22 let loadedmetadataListener; 23 24 const { prototype } = window.wrappedJSObject.EventTarget; 25 const { addEventListener, dispatchEvent } = prototype; 26 27 Object.defineProperty(prototype, "addEventListener", { 28 value: exportFunction(function (type, listener, cfg) { 29 if (type?.toLowerCase() === "loadedmetadata") { 30 loadedmetadataListener = listener; 31 return addEventListener.call( 32 this, 33 type, 34 exportFunction(e => { 35 loadedmetadataEvent = e; 36 }, window), 37 cfg 38 ); 39 } 40 return addEventListener.call(this, type, listener, cfg); 41 }, window), 42 }); 43 44 Object.defineProperty(prototype, "dispatchEvent", { 45 value: exportFunction(function (e) { 46 if ( 47 e?.type === "GAME_READY" && 48 loadedmetadataEvent && 49 loadedmetadataListener 50 ) { 51 try { 52 (loadedmetadataListener?.handleEvent ?? loadedmetadataListener)( 53 loadedmetadataEvent 54 ); 55 } catch (_) { 56 console.trace(_); 57 } 58 loadedmetadataListener = undefined; 59 loadedmetadataEvent = undefined; 60 } 61 return dispatchEvent.call(this, e); 62 }, window), 63 });