1
0
mirror of https://github.com/laurent22/joplin.git synced 2024-12-18 09:35:20 +02:00
joplin/packages/app-mobile/utils/ipc/RNToWebViewMessenger.ts
Henry Heino 55cafb8891
Android: Add support for Markdown editor plugins (#10086)
Co-authored-by: Laurent Cozic <laurent22@users.noreply.github.com>
2024-03-11 15:02:15 +00:00

52 lines
1.6 KiB
TypeScript

import RemoteMessenger from '@joplin/lib/utils/ipc/RemoteMessenger';
import { SerializableData } from '@joplin/lib/utils/ipc/types';
import { WebViewMessageEvent } from 'react-native-webview';
import { WebViewControl } from '../../components/ExtendedWebView';
import { RefObject } from 'react';
export default class RNToWebViewMessenger<LocalInterface, RemoteInterface> extends RemoteMessenger<LocalInterface, RemoteInterface> {
public constructor(channelId: string, private webviewControl: WebViewControl|RefObject<WebViewControl>, localApi: LocalInterface) {
super(channelId, localApi);
}
protected override postMessage(message: SerializableData): void {
const webviewControl = (this.webviewControl as RefObject<WebViewControl>).current ?? (this.webviewControl as WebViewControl);
// This can happen just after the WebView unloads.
if (!webviewControl) return;
// This is the case in testing environments where no WebView is available.
if (!webviewControl.injectJS) return;
webviewControl.injectJS(`
window.dispatchEvent(
new MessageEvent(
'message',
{
data: ${JSON.stringify(message)},
origin: 'react-native'
},
),
);
`);
}
public onWebViewMessage = (event: WebViewMessageEvent) => {
if (!this.hasBeenClosed()) {
void this.onMessage(JSON.parse(event.nativeEvent.data));
}
};
public onWebViewLoaded = () => {
// Send onReadyToReceive again (if needed).
//
// This is necessary because any events sent before the webview finished loading
// may not have been delivered (though they may have).
this.onReadyToReceive();
};
protected override onClose(): void {
}
}