Skip to content

Commit

Permalink
Start listening in 0-indent scope
Browse files Browse the repository at this point in the history
  • Loading branch information
JiriLojda committed Dec 4, 2024
1 parent 1ae17b7 commit c758e8e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 20 deletions.
11 changes: 3 additions & 8 deletions src/customAppSdk.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { sendMessage, startListening } from "./iframeMessenger";
import { sendMessage } from "./iframeMessenger";
import { ErrorMessage } from "./iframeSchema";
import { matchesSchema } from "./matchesSchema";

Expand Down Expand Up @@ -26,10 +26,8 @@ export type CustomAppContext =
readonly description: string;
};

export const getCustomAppContext = (): Promise<CustomAppContext> => {
const stopListening = startListening();

return new Promise((resolve, reject) => {
export const getCustomAppContext = (): Promise<CustomAppContext> =>
new Promise((resolve, reject) => {
try {
sendMessage<"[email protected]">(
{
Expand All @@ -47,8 +45,5 @@ export const getCustomAppContext = (): Promise<CustomAppContext> => {
);
} catch (error) {
reject(error);
} finally {
stopListening();
}
});
};
18 changes: 6 additions & 12 deletions src/iframeMessenger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,6 @@ import type { AllClientResponses } from "./utilityTypes";

let callbacks: Readonly<Record<string, (data: unknown) => void>> = {};

export const startListening = (): (() => void) => {
if (window.self === window.top) {
throw new Error("Custom app is not hosted in an IFrame.");
}

window.addEventListener("message", processMessage, true);

return () => {
window.removeEventListener("message", processMessage, true);
};
};

export const sendMessage = <TMessageType extends keyof Schema["client"]>(
message: Omit<Schema["client"][TMessageType]["request"], "requestId">,
callback: (data: Schema["client"][TMessageType]["response"]) => void,
Expand All @@ -33,3 +21,9 @@ const processMessage = (event: MessageEvent<AllClientResponses>): void => {
);
callback?.(message);
};

if (window.self === window.top) {
throw new Error("Custom app is not hosted in an IFrame.");
}

window.addEventListener("message", processMessage, true);

0 comments on commit c758e8e

Please sign in to comment.