/* eslint-env browser */ import * as React from "react"; import { useRef } from "react"; import { arrayOf, object, func, shape, string } from "prop-types"; import { WebView, WebViewNavigation } from "react-native-webview"; import WebApiBridge from "@precor/web-api-bridge"; //import { useNavigation } from "@react-navigation/native"; // postMessage() results in the webapp getting the message on the document // object in android and the window object in ios. Since react-native-webvew // has deprecated the webview object postMessage() function anyway, we'll // inject this iffy as a replacement when the webview object becomes available. const dispatchMessageEvent = (data: any) => `(function() { window.dispatchEvent(new MessageEvent('message', { data: ${JSON.stringify(data)} })); })()`; function WebViewApi({ apis, setSend, listener, ...rest }: any) { const webApiBridge = new WebApiBridge(); const webViewRef = useRef(); webApiBridge.apis = apis; setSend(webApiBridge.send.bind(webApiBridge)); webApiBridge.listener = listener; const onMessage = (event: any) => { webApiBridge.onMessage(event, event.nativeEvent.data); }; //const navigation = useNavigation(); function onChangeNavitationState(e: WebViewNavigation) { if (e.url !== rest.source.uri) { webViewRef.current?.stopLoading(); //navigation.navigate("nav-web-view", { url: e.url, title: "Popup" }); } } return ( { if (webView) { webView.postMessage = (message: string) => webView.injectJavaScript(dispatchMessageEvent(message)); webApiBridge.target = webView; webViewRef.current = webView; } }} onMessage={onMessage} scrollEnabled={false} automaticallyAdjustContentInsets={false} bounces={false} onError={(err) => { console.log(err); }} /> ); } WebViewApi.propTypes = { apis: arrayOf(object).isRequired, setSend: func.isRequired, source: shape({ uri: string }).isRequired, listener: func, }; WebViewApi.defaultProps = { listener: undefined, }; export default WebViewApi;