From c758e8e001b631a8d6ccfcb9665996c90d87585c Mon Sep 17 00:00:00 2001 From: Jiri Lojda Date: Wed, 4 Dec 2024 11:36:48 +0100 Subject: [PATCH] Start listening in 0-indent scope --- src/customAppSdk.ts | 11 +++-------- src/iframeMessenger.ts | 18 ++++++------------ 2 files changed, 9 insertions(+), 20 deletions(-) diff --git a/src/customAppSdk.ts b/src/customAppSdk.ts index 9060ca9..9bb5e56 100644 --- a/src/customAppSdk.ts +++ b/src/customAppSdk.ts @@ -1,4 +1,4 @@ -import { sendMessage, startListening } from "./iframeMessenger"; +import { sendMessage } from "./iframeMessenger"; import { ErrorMessage } from "./iframeSchema"; import { matchesSchema } from "./matchesSchema"; @@ -26,10 +26,8 @@ export type CustomAppContext = readonly description: string; }; -export const getCustomAppContext = (): Promise => { - const stopListening = startListening(); - - return new Promise((resolve, reject) => { +export const getCustomAppContext = (): Promise => + new Promise((resolve, reject) => { try { sendMessage<"get-context@1.0.0">( { @@ -47,8 +45,5 @@ export const getCustomAppContext = (): Promise => { ); } catch (error) { reject(error); - } finally { - stopListening(); } }); -}; diff --git a/src/iframeMessenger.ts b/src/iframeMessenger.ts index ce5ceeb..d6962ea 100644 --- a/src/iframeMessenger.ts +++ b/src/iframeMessenger.ts @@ -4,18 +4,6 @@ import type { AllClientResponses } from "./utilityTypes"; let callbacks: Readonly 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 = ( message: Omit, callback: (data: Schema["client"][TMessageType]["response"]) => void, @@ -33,3 +21,9 @@ const processMessage = (event: MessageEvent): void => { ); callback?.(message); }; + +if (window.self === window.top) { + throw new Error("Custom app is not hosted in an IFrame."); +} + +window.addEventListener("message", processMessage, true);