Improve webview state

This commit is contained in:
Arnaud Vergnet 2021-05-09 15:06:45 +02:00
parent 128af0b813
commit 7a58ce6b70

View file

@ -24,7 +24,7 @@ import React, {
useRef, useRef,
useState, useState,
} from 'react'; } from 'react';
import WebView from 'react-native-webview'; import WebView, { WebViewNavigation } from 'react-native-webview';
import { import {
Divider, Divider,
HiddenItem, HiddenItem,
@ -71,8 +71,15 @@ const styles = StyleSheet.create({
* Class defining a webview screen. * Class defining a webview screen.
*/ */
function WebViewScreen(props: Props) { function WebViewScreen(props: Props) {
const [currentUrl, setCurrentUrl] = useState(props.url); const [navState, setNavState] = useState<undefined | WebViewNavigation>({
const [canGoBack, setCanGoBack] = useState(false); canGoBack: false,
canGoForward: false,
loading: true,
url: props.url,
lockIdentifier: 0,
navigationType: 'click',
title: '',
});
const navigation = useNavigation(); const navigation = useNavigation();
const theme = useTheme(); const theme = useTheme();
const webviewRef = useRef<WebView>(); const webviewRef = useRef<WebView>();
@ -109,7 +116,7 @@ function WebViewScreen(props: Props) {
: getBasicButton, : getBasicButton,
}); });
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [navigation, props.showAdvancedControls]); }, [navigation, props.showAdvancedControls, navState?.url]);
useEffect(() => { useEffect(() => {
if (props.injectJS && props.injectJS !== currentInjectedJS) { if (props.injectJS && props.injectJS !== currentInjectedJS) {
@ -120,7 +127,7 @@ function WebViewScreen(props: Props) {
}, [props.injectJS]); }, [props.injectJS]);
const onBackButtonPressAndroid = () => { const onBackButtonPressAndroid = () => {
if (canGoBack) { if (navState?.canGoBack) {
onGoBackClicked(); onGoBackClicked();
return true; return true;
} }
@ -217,7 +224,8 @@ function WebViewScreen(props: Props) {
} }
}; };
const onOpenClicked = () => Linking.openURL(currentUrl); const onOpenClicked = () =>
navState ? Linking.openURL(navState.url) : undefined;
const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => { const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
if (props.onScroll) { if (props.onScroll) {
@ -247,10 +255,7 @@ function WebViewScreen(props: Props) {
onRefresh={onRefreshClicked} onRefresh={onRefreshClicked}
/> />
)} )}
onNavigationStateChange={(navState) => { onNavigationStateChange={setNavState}
setCurrentUrl(navState.url);
setCanGoBack(navState.canGoBack);
}}
onMessage={props.onMessage} onMessage={props.onMessage}
onLoad={() => injectJavaScript(getJavascriptPadding(containerPaddingTop))} onLoad={() => injectJavaScript(getJavascriptPadding(containerPaddingTop))}
// Animations // Animations