Browse Source

Improve webview state

Arnaud Vergnet 2 years ago
parent
commit
7a58ce6b70
1 changed files with 15 additions and 10 deletions
  1. 15
    10
      src/components/Screens/WebViewScreen.tsx

+ 15
- 10
src/components/Screens/WebViewScreen.tsx View File

@@ -24,7 +24,7 @@ import React, {
24 24
   useRef,
25 25
   useState,
26 26
 } from 'react';
27
-import WebView from 'react-native-webview';
27
+import WebView, { WebViewNavigation } from 'react-native-webview';
28 28
 import {
29 29
   Divider,
30 30
   HiddenItem,
@@ -71,8 +71,15 @@ const styles = StyleSheet.create({
71 71
  * Class defining a webview screen.
72 72
  */
73 73
 function WebViewScreen(props: Props) {
74
-  const [currentUrl, setCurrentUrl] = useState(props.url);
75
-  const [canGoBack, setCanGoBack] = useState(false);
74
+  const [navState, setNavState] = useState<undefined | WebViewNavigation>({
75
+    canGoBack: false,
76
+    canGoForward: false,
77
+    loading: true,
78
+    url: props.url,
79
+    lockIdentifier: 0,
80
+    navigationType: 'click',
81
+    title: '',
82
+  });
76 83
   const navigation = useNavigation();
77 84
   const theme = useTheme();
78 85
   const webviewRef = useRef<WebView>();
@@ -109,7 +116,7 @@ function WebViewScreen(props: Props) {
109 116
         : getBasicButton,
110 117
     });
111 118
     // eslint-disable-next-line react-hooks/exhaustive-deps
112
-  }, [navigation, props.showAdvancedControls]);
119
+  }, [navigation, props.showAdvancedControls, navState?.url]);
113 120
 
114 121
   useEffect(() => {
115 122
     if (props.injectJS && props.injectJS !== currentInjectedJS) {
@@ -120,7 +127,7 @@ function WebViewScreen(props: Props) {
120 127
   }, [props.injectJS]);
121 128
 
122 129
   const onBackButtonPressAndroid = () => {
123
-    if (canGoBack) {
130
+    if (navState?.canGoBack) {
124 131
       onGoBackClicked();
125 132
       return true;
126 133
     }
@@ -217,7 +224,8 @@ function WebViewScreen(props: Props) {
217 224
     }
218 225
   };
219 226
 
220
-  const onOpenClicked = () => Linking.openURL(currentUrl);
227
+  const onOpenClicked = () =>
228
+    navState ? Linking.openURL(navState.url) : undefined;
221 229
 
222 230
   const onScroll = (event: NativeSyntheticEvent<NativeScrollEvent>) => {
223 231
     if (props.onScroll) {
@@ -247,10 +255,7 @@ function WebViewScreen(props: Props) {
247 255
           onRefresh={onRefreshClicked}
248 256
         />
249 257
       )}
250
-      onNavigationStateChange={(navState) => {
251
-        setCurrentUrl(navState.url);
252
-        setCanGoBack(navState.canGoBack);
253
-      }}
258
+      onNavigationStateChange={setNavState}
254 259
       onMessage={props.onMessage}
255 260
       onLoad={() => injectJavaScript(getJavascriptPadding(containerPaddingTop))}
256 261
       // Animations

Loading…
Cancel
Save