frontend: refactor message handling to use bound method for event listener

This commit is contained in:
Carlos Santos 2025-05-12 11:15:24 +02:00
parent 6c9e1d9b50
commit 41e7b645ee

View File

@ -21,6 +21,7 @@ import { OutboundEventMessage, InboundCommandMessage } from 'webcomponent/src/mo
})
export class WebComponentManagerService {
protected isListenerStarted = false;
protected boundHandleMessage: (event: MessageEvent) => Promise<void>;
protected log;
constructor(
@ -31,6 +32,7 @@ export class WebComponentManagerService {
protected httpService: HttpService
) {
this.log = this.loggerService.get('OpenVidu Meet - WebComponentManagerService');
this.boundHandleMessage = this.handleMessage.bind(this);
}
startCommandsListener(): void {
@ -38,7 +40,25 @@ export class WebComponentManagerService {
this.isListenerStarted = true;
// Listen for messages from the iframe
window.addEventListener('message', async (event) => {
window.addEventListener('message', this.boundHandleMessage);
this.log.d('Started commands listener');
}
stopCommandsListener(): void {
if (!this.isListenerStarted) return;
this.isListenerStarted = false;
window.removeEventListener('message', this.boundHandleMessage);
this.log.d('Stopped commands listener');
}
sendMessageToParent(event: OutboundEventMessage) {
if (!this.contextService.isEmbeddedMode()) return;
this.log.d('Sending message to parent :', event);
const origin = this.contextService.getParentDomain();
window.parent.postMessage(event, origin);
}
protected async handleMessage(event: MessageEvent): Promise<void> {
const message: InboundCommandMessage = event.data;
const parentDomain = this.contextService.getParentDomain();
const { command, payload } = message;
@ -81,19 +101,5 @@ export class WebComponentManagerService {
default:
break;
}
});
}
stopCommandsListener(): void {
if (!this.isListenerStarted) return;
this.isListenerStarted = false;
window.removeEventListener('message', this.startCommandsListener);
}
sendMessageToParent(event: OutboundEventMessage) {
if (!this.contextService.isEmbeddedMode()) return;
this.log.d('Sending message to parent :', event);
const origin = this.contextService.getParentDomain();
window.parent.postMessage(event, origin);
}
}