const emote_regex = /bttv:([^\s]+)/g; type Emote = { code: string; url: string; }; async function bttv_get_url(code: string): Promise { return { code: code, url: `result_${code}`, }; } type EmoteMap = { [code: string]: string }; async function get_emotes(codes: Iterable): Promise { const codes_set = new Set(codes); // queue emote jobs const queue = [...codes_set].map((code) => bttv_get_url(code)); // run const result: EmoteMap = {}; for (const job of await Promise.all(queue)) { result[job.code] = job.url; } return result; } async function process_text(text: string): Promise { const matches = [...text.matchAll(emote_regex)]; const emotes = await get_emotes(matches.map((elem) => elem[1])); for (const emote of matches.reverse()) { const [match, code] = emote; const index = emote.index ?? 0; text = text.substring(0, index) + emotes[code] + text.substring(index + match.length); } console.log(text); return text; } (() => { const cb_form = document.querySelector("#mgc_cb_evo_form"); if (!(cb_form instanceof HTMLFormElement)) return; const bttv_btn = (() => { const btn = document.createElement("a"); btn.style.setProperty("cursor", "pointer"); btn.style.setProperty("margin-right", "4px"); const img = document.createElement("img"); img.setAttribute("src", chrome.runtime.getURL("bttv.png")); img.style.setProperty("vertical-align", "middle"); btn.addEventListener("click", async (event) => { const cb_input = document.querySelector("#mgc_cb_evo_input"); if (!(cb_input instanceof HTMLInputElement)) return; await process_text("bttv:foo bttv:bar bttv:foo"); // await process_text(cb_input.value); // cb_input.focus(); }); btn.appendChild(img); return btn; })(); cb_form.insertBefore( bttv_btn, document.querySelector("#mgc_cb_evo_form > input[type=image]:nth-child(2)"), ); console.log("done."); })();