Bug: Safe app communicator is not properly initialized sometimes, thus app fails to communicate (#2069)

* use iframeRef inside app communicator
This commit is contained in:
Mikhail Mikheev 2021-03-22 20:59:12 +03:00 committed by GitHub
parent c41ab4eaec
commit 253137d2ba
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -15,12 +15,12 @@ type MessageHandler = (
) => void | MethodToResponse[Methods] | ErrorResponse | Promise<MethodToResponse[Methods] | ErrorResponse | void> ) => void | MethodToResponse[Methods] | ErrorResponse | Promise<MethodToResponse[Methods] | ErrorResponse | void>
class AppCommunicator { class AppCommunicator {
private iframe: HTMLIFrameElement private iframeRef: MutableRefObject<HTMLIFrameElement | null>
private handlers = new Map<Methods, MessageHandler>() private handlers = new Map<Methods, MessageHandler>()
private app: SafeApp private app: SafeApp
constructor(iframeRef: MutableRefObject<HTMLIFrameElement>, app: SafeApp) { constructor(iframeRef: MutableRefObject<HTMLIFrameElement | null>, app: SafeApp) {
this.iframe = iframeRef.current this.iframeRef = iframeRef
this.app = app this.app = app
window.addEventListener('message', this.handleIncomingMessage) window.addEventListener('message', this.handleIncomingMessage)
@ -49,7 +49,7 @@ class AppCommunicator {
? MessageFormatter.makeErrorResponse(requestId, data, sdkVersion) ? MessageFormatter.makeErrorResponse(requestId, data, sdkVersion)
: MessageFormatter.makeResponse(requestId, data, sdkVersion) : MessageFormatter.makeResponse(requestId, data, sdkVersion)
this.iframe.contentWindow?.postMessage(msg, this.app.url) this.iframeRef.current?.contentWindow?.postMessage(msg, this.app.url)
} }
handleIncomingMessage = async (msg: SDKMessageEvent): Promise<void> => { handleIncomingMessage = async (msg: SDKMessageEvent): Promise<void> => {
@ -83,7 +83,6 @@ const useAppCommunicator = (
app?: SafeApp, app?: SafeApp,
): AppCommunicator | undefined => { ): AppCommunicator | undefined => {
const [communicator, setCommunicator] = useState<AppCommunicator | undefined>(undefined) const [communicator, setCommunicator] = useState<AppCommunicator | undefined>(undefined)
useEffect(() => { useEffect(() => {
let communicatorInstance let communicatorInstance
const initCommunicator = (iframeRef: MutableRefObject<HTMLIFrameElement>, app: SafeApp) => { const initCommunicator = (iframeRef: MutableRefObject<HTMLIFrameElement>, app: SafeApp) => {
@ -91,7 +90,7 @@ const useAppCommunicator = (
setCommunicator(communicatorInstance) setCommunicator(communicatorInstance)
} }
if (app && iframeRef.current !== null) { if (app) {
initCommunicator(iframeRef as MutableRefObject<HTMLIFrameElement>, app) initCommunicator(iframeRef as MutableRefObject<HTMLIFrameElement>, app)
} }