2024-03-11 17:02:15 +02:00
|
|
|
import RemoteMessenger from './RemoteMessenger';
|
|
|
|
import { SerializableData } from './types';
|
|
|
|
|
2024-08-02 15:51:49 +02:00
|
|
|
// This allows using a WindowMessenger in a web worker, with window-like objects.
|
|
|
|
const getLocalWindow = () => {
|
|
|
|
return typeof window !== 'undefined' ? window : self;
|
|
|
|
};
|
|
|
|
|
2024-03-11 17:02:15 +02:00
|
|
|
export default class WindowMessenger<LocalInterface, RemoteInterface> extends RemoteMessenger<LocalInterface, RemoteInterface> {
|
|
|
|
public constructor(channelId: string, private remoteWindow: Window, localApi: LocalInterface|null) {
|
|
|
|
super(channelId, localApi);
|
|
|
|
|
2024-08-02 15:51:49 +02:00
|
|
|
getLocalWindow().addEventListener('message', this.handleMessageEvent);
|
2024-03-11 17:02:15 +02:00
|
|
|
|
|
|
|
this.onReadyToReceive();
|
|
|
|
}
|
|
|
|
|
|
|
|
private handleMessageEvent = (event: MessageEvent) => {
|
|
|
|
if (event.source !== this.remoteWindow) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
void this.onMessage(event.data);
|
|
|
|
};
|
|
|
|
|
|
|
|
protected override postMessage(message: SerializableData): void {
|
|
|
|
this.remoteWindow.postMessage(message, '*');
|
|
|
|
}
|
|
|
|
|
|
|
|
protected override onClose(): void {
|
2024-08-02 15:51:49 +02:00
|
|
|
getLocalWindow().removeEventListener('message', this.handleMessageEvent);
|
2024-03-11 17:02:15 +02:00
|
|
|
}
|
|
|
|
}
|