[bug] make MessageBus more reliable

This commit is contained in:
Sosthene 2025-07-15 21:18:44 +02:00
parent b7f725bcfd
commit 97e86308ce
3 changed files with 24 additions and 36 deletions

View File

@ -12,9 +12,6 @@ function Iframe({ showIframe = false }: IframeProps) {
if (iframeRef.current) {
IframeReference.setIframe(iframeRef.current);
}
return () => {
IframeReference.setIframe(null);
};
}, [iframeRef.current]);
return (

View File

@ -5,6 +5,11 @@ export default class IframeReference {
private constructor() { }
public static setTargetOrigin(targetOrigin: string): void {
if (this.targetOrigin) {
console.debug("targetOrigin is already set");
return;
}
try {
new URL(targetOrigin);
this.targetOrigin = targetOrigin;

View File

@ -759,17 +759,15 @@ export default class MessageBus {
}
private sendMessage(message: any): void {
const targetOrigin = IframeReference.getTargetOrigin();
if (!targetOrigin) {
console.error('[MessageBus] sendMessage: targetOrigin not found');
return;
}
const iframe = IframeReference.getIframe();
if (!iframe) {
console.error('[MessageBus] sendMessage: iframe not found');
return;
}
iframe.contentWindow?.postMessage(message, targetOrigin);
this.isReady().then(() => {
try {
const targetOrigin = IframeReference.getTargetOrigin();
const iframe = IframeReference.getIframe();
iframe.contentWindow?.postMessage(message, targetOrigin);
} catch (error) {
console.error('[MessageBus] sendMessage: error', error);
}
}).catch(console.error);
}
private handleMessage(event: MessageEvent): void {
@ -777,30 +775,18 @@ export default class MessageBus {
return;
}
const iframe = IframeReference.getIframe();
if (!iframe) {
console.error('[MessageBus] handleMessage: iframe not found');
return;
}
try {
const targetOrigin = IframeReference.getTargetOrigin();
if (event.source !== iframe.contentWindow) {
console.error('[MessageBus] handleMessage: source not match');
return;
}
if (event.origin !== targetOrigin) {
throw new Error(`origin don't match: expected ${targetOrigin}, got ${event.origin} with type ${event.data.type}`);
}
const targetOrigin = IframeReference.getTargetOrigin();
if (!targetOrigin) {
console.error('[MessageBus] handleMessage: targetOrigin not found');
return;
}
if (event.origin !== targetOrigin) {
console.error('[MessageBus] handleMessage: origin not match');
return;
}
if (!event.data || typeof event.data !== 'object') {
console.error('[MessageBus] handleMessage: data not found');
if (!event.data || typeof event.data !== 'object') {
throw new Error('data not found');
}
} catch (error) {
console.error('[MessageBus] handleMessage:', error);
return;
}