[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) { if (iframeRef.current) {
IframeReference.setIframe(iframeRef.current); IframeReference.setIframe(iframeRef.current);
} }
return () => {
IframeReference.setIframe(null);
};
}, [iframeRef.current]); }, [iframeRef.current]);
return ( return (

View File

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

View File

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