Skip to content

Commit

Permalink
chore: simplify embed page
Browse files Browse the repository at this point in the history
  • Loading branch information
darlanalves authored Jul 31, 2024
1 parent 516f8ac commit 750ffc7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 14 deletions.
20 changes: 19 additions & 1 deletion assets/lib.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ async function deleteProperty(key) {
return toBoolean(r);
}

export const commands = {
const commands = {
getProfile,
isAuthenticated,
signOut,
Expand All @@ -80,3 +80,21 @@ export const commands = {
setProperty,
deleteProperty,
};

/**
* @param {MessageEvent} event
*/
export async function runCommand(event) {
const { command, args, id } = event.data;

try {
if (command in commands === false) {
throw new Error('Invalid command: ' + command);
}

const result = await commands[command].apply(null, args);
event.source.postMessage({ event: 'success', detail: { id, result } }, event.origin);
} catch (error) {
event.source.postMessage({ event: 'error', detail: { id, error } }, event.origin);
}
}
15 changes: 2 additions & 13 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,26 +115,15 @@ async function makeEmbedPage(_req, res) {
.map((s) => s.trim());

res.send(`<script type="module">
import { commands } from '/lib.mjs';
import { runCommand } from '/lib.mjs';
const allowedOrigins = ${JSON.stringify(allowedOrigins)};
window.addEventListener("message", async function (event) {
if (!allowedOrigins.some(o => event.origin.endsWith(o))) {
console.log('Origin not allowed: ' + event.origin, event);
return;
}
const { command, args, id } = event.data;
try {
if (command in commands === false) {
throw new Error('Invalid command: ' + command);
}
const result = await commands[command].apply(null, args);
event.source.postMessage({ event: 'success', detail: { id, result } }, event.origin);
} catch (error) {
event.source.postMessage({ event: 'error', detail: { id, error } }, event.origin);
}
runCommand(event);
}, false);
</script>`);
}
Expand Down

0 comments on commit 750ffc7

Please sign in to comment.