2020-11-27 01:31:31 +02:00
|
|
|
import Logger from '@joplin/lib/Logger';
|
2020-11-16 18:14:26 +02:00
|
|
|
import { useEffect } from 'react';
|
|
|
|
|
2020-11-27 01:31:31 +02:00
|
|
|
const logger = Logger.create('useWebviewToPluginMessages');
|
|
|
|
|
|
|
|
export default function(frameWindow: any, isReady: boolean, onMessage: Function, pluginId: string, viewId: string) {
|
2020-11-16 18:14:26 +02:00
|
|
|
useEffect(() => {
|
|
|
|
if (!frameWindow) return () => {};
|
|
|
|
|
2020-11-27 01:31:31 +02:00
|
|
|
function onMessage_(event: any) {
|
2020-11-16 18:14:26 +02:00
|
|
|
if (!event.data || event.data.target !== 'plugin') return;
|
2020-11-27 01:31:31 +02:00
|
|
|
|
|
|
|
// The message is passed from one component or service to the next
|
|
|
|
// till it reaches its destination, so if something doesn't work
|
|
|
|
// follow the chain of messages searching for the string "Got message"
|
|
|
|
logger.debug('Got message (WebView => Plugin) (1)', pluginId, viewId, event.data.message);
|
|
|
|
|
2020-11-16 18:14:26 +02:00
|
|
|
onMessage({
|
|
|
|
pluginId: pluginId,
|
|
|
|
viewId: viewId,
|
|
|
|
message: event.data.message,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-11-27 01:31:31 +02:00
|
|
|
frameWindow.addEventListener('message', onMessage_);
|
2020-11-16 18:14:26 +02:00
|
|
|
|
|
|
|
return () => {
|
2020-11-27 01:31:31 +02:00
|
|
|
frameWindow.removeEventListener('message', onMessage_);
|
2020-11-16 18:14:26 +02:00
|
|
|
};
|
2020-11-27 01:31:31 +02:00
|
|
|
}, [frameWindow, onMessage, isReady, pluginId, viewId]);
|
2020-11-16 18:14:26 +02:00
|
|
|
}
|