2024-03-11 17:02:15 +02:00
|
|
|
|
|
|
|
import RemoteMessenger from '@joplin/lib/utils/ipc/RemoteMessenger';
|
|
|
|
import { SerializableData } from '@joplin/lib/utils/ipc/types';
|
|
|
|
|
2024-08-02 15:51:49 +02:00
|
|
|
interface ExtendedWindow extends Window {
|
|
|
|
ReactNativeWebView: {
|
|
|
|
postMessage(message: unknown): void;
|
|
|
|
supportsNonStringMessages?: boolean;
|
|
|
|
};
|
|
|
|
}
|
|
|
|
declare const window: ExtendedWindow;
|
|
|
|
|
2024-03-11 17:02:15 +02:00
|
|
|
export default class WebViewToRNMessenger<LocalInterface, RemoteInterface> extends RemoteMessenger<LocalInterface, RemoteInterface> {
|
|
|
|
public constructor(channelId: string, localApi: LocalInterface) {
|
|
|
|
super(channelId, localApi);
|
|
|
|
|
|
|
|
window.addEventListener('message', this.handleMessage);
|
|
|
|
|
|
|
|
// Allow the event loop to run -- without this, calling
|
|
|
|
// injectJS('window.handleReactNativeMessage("message")')
|
|
|
|
// in ReactNative can (but doesn't always) fail if called immediately after
|
|
|
|
// sending ReadyToReceive.
|
|
|
|
setTimeout(() => {
|
|
|
|
this.onReadyToReceive();
|
|
|
|
}, 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
private handleMessage = (message: MessageEvent) => {
|
|
|
|
if (typeof message.data === 'object' && message.origin === 'react-native') {
|
|
|
|
void this.onMessage(message.data);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
protected override postMessage(message: SerializableData): void {
|
2024-08-02 15:51:49 +02:00
|
|
|
window.ReactNativeWebView.postMessage(window.ReactNativeWebView.supportsNonStringMessages ? message : JSON.stringify(message));
|
2024-03-11 17:02:15 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
protected override onClose(): void {
|
|
|
|
window.removeEventListener('message', this.handleMessage);
|
|
|
|
}
|
|
|
|
}
|