Reading from CodeMirror:
export function executeInPage(code: string): Promise<any> {
return new Promise((resolve, reject) => {
const script = document.createElement("script");
const eventId = (new URL(browser.runtime.getURL(""))).hostname + Math.random();
script.innerHTML = `(async (evId) => {
try {
let result;
result = await ${code};
window.dispatchEvent(new CustomEvent(evId, {
detail: {
success: true,
result,
}
}));
} catch (e) {
window.dispatchEvent(new CustomEvent(evId, {
detail: { success: false, reason: e },
}));
}
})(${JSON.stringify(eventId)})`;
window.addEventListener(eventId, ({ detail }: any) => {
script.parentNode.removeChild(script);
if (detail.success) {
return resolve(detail.result);
}
return reject(detail.reason);
}, { once: true });
document.head.appendChild(script);
});
}
executeInPage(`(()=>{return document.getElementById(Id).CodeMirror.getValue()})`);