Skip to content

[android] Blank screen flash when navigating back to screen containing webview. #12

Open

Description

@nat-gaurav-saini

Bug description:

Screen containing webview flashes white when navigating back from any other screen. Native component do not flash. Only the webview flashes.

To Reproduce:

Setup two screens A & B using stack navigator. Either screen A or both screen should contain a webview.
Navigate to screen B from screen A.
Hit hardware back press to go back to screen A.
Screen A flashes white for a moment.
Expected behavior:

There should not be a white flash when navigating back to already rendered screen containing a webview.

Screenshots/Videos:
https://streamable.com/33nspv

Environment:

OS:android
OS version:15
react-native version:0.76.6
react-native-webview version: 13.15.1

Activity

  1. added
    P1
    on Jan 29, 2025
  2. birdofpreyru commented on Jan 29, 2025

    @birdofpreyru
    Owner

    @nat-gaurav-saini have you tried whether the same happens with RN@0.77? and with this lib's older version (v13.14.1) with RN@0.76.6?

  3. nat-gaurav-saini commented on Jan 29, 2025

    @nat-gaurav-saini
    Author

    Same issue with latest RNW@13.15.1 & RN@0.77

    The issue is more prominent with slower device. Here is screen recording from Oneplus Nord CE and latest libs
    https://streamable.com/8xr6kb

  4. nat-gaurav-saini commented on Jan 29, 2025

    @nat-gaurav-saini
    Author

    For reference, this is how I am utilizing webview!

    import { router, useSegments } from 'expo-router';
    import { useEffect, useState, useRef } from 'react';
    import { WebView } from '@dr.pogodin/react-native-webview';
    import { Platform } from 'react-native';
    
    import { useCartStore, useUserStore, useWebviewStore, cartResetState } from '@/stores/store';
    
    import ContentLoader from '@/components/layout/ContentLoader';
    
    const WebviewWrapper = ({ onScrollHandler, uri, style = {}, baseRef = null }) => {
      const segments = useSegments();
      const handleWebViewLoadStart = useWebviewStore((state) => state.handleWebViewLoadStart);
      // const { injectedJavaScriptWebView, setInjectedJavascriptWebView } = useAppContext();
      const [loading, setLoading] = useState(false);
      const [webViewURI, setWebViewURI] = useState(uri);
    
      useEffect(() => {
        if (baseRef) {
          // web_ref.current.ref_id = refKey;
          useWebviewStore.setState({ webViewRef: baseRef });
        }
      }, [baseRef]);
    
      useEffect(() => {
        setWebViewURI(uri);
        // called when component is unmounted
        return () => {
          setWebViewURI(null);
        };
      }, [uri]);
    
      // main navigation handler of webview
      // returns true for loading web view request and false to stop loading
      // uri -> on which page should be redirected(getting as prop from web view)
      // webviewurl -> url from web view navigation
      const handleNavigationChange = (webViewNavigationState) => {
        // console.log('handleNavigationChange');
        // setLoading(true);
        let webViewUrl = webViewNavigationState.url;
        let urlPathname = new URL(webViewNavigationState.url).pathname;
        let urlSearchParams = new URL(webViewNavigationState.url).searchParams;
        // console.log('urlPathname', urlPathname);
        // console.log('arguement url', uri);
        // console.log('webViewUrl', webViewUrl);
    
        if (webViewUrl.includes('/undefined') || webViewUrl.includes(null)) {
          return false;
        }
        if (webViewUrl == 'about:blank' || webViewUrl == 'about:srcdoc') {
          return true;
        }
    
        if (webViewUrl !== webViewURI) {
          if (urlPathname === '/') {
            return true;
          }
          const pathSplit = urlPathname.split('/');
          console.log('pathSplit', pathSplit);
          if (pathSplit.includes('products')) {
            let productUrl = pathSplit[pathSplit.length - 1];
            if (segments[1] == 'profile') {
              router.push({
                pathname: `/(categories)/products/${productUrl}`,
              });
            } else {
              router.push({
                pathname: `/${segments[1]}/products/${productUrl}`,
              });
            }
            return false;
          } else if (pathSplit.includes('thank_you') && pathSplit.includes('placed')) {
            let chkId = urlSearchParams.get('chk_id');
            // router.push({
            //   pathname: `/cart/thankyou/${chkId}`,
            // });
            return false;
          } else if (pathSplit.includes('pages')) {
            if (pathSplit.includes('all-categories')) {
              return false;
            } else if (pathSplit.includes('menu')) {
              router.push({
                pathname: `/profile`,
              });
              return false;
            } else if (pathSplit.includes('face-scan')) {
              router.push({
                pathname: `/pages/face-scan`,
              });
              return false;
            } else {
              return false;
            }
          } else return true;
        }
        return true;
      };
    
      const webPostMessageHandler = (e) => {
        const events = JSON.parse(e.nativeEvent.data);
        if (events.type == 'Console') {
          console.log(`[Console] ${JSON.stringify(events.data)}`);
        }
    
        if (events.action === 'login-menu') {
          useUserStore.getState().handleLoginModal();
        } else if (events.action === 'login') {
          useUserStore.getState().handleLoginModal();
        }
    
        if (events.action === 'logout') {
          useUserStore.getState().handleLogout();
        }
    
        if (events.action === 'goToCart' && events.data) {
          useCartStore.setState({
            showGoToCart: true,
            cartItems: events.data.items,
            cartCosting: events.data.costing,
            cartItemCount: events.data.itemCount,
            cartSuggestions: events.data.cartSuggestions,
          });
        }
        if (events.action === 'addToCart' && events.data) {
          useCartStore.setState({
            cartItems: events.data.items,
            cartCosting: events.data.costing,
            cartItemCount: events.data.itemCount,
            cartSuggestions: events.data.cartSuggestions,
            showGoToCart: events.data.showGoToCart,
            isCartEmpty: false,
          });
        }
        if (events.action === 'removeFromCart' && events.data) {
          if (events.data.itemCount === 0 || !events.data.itemCount) {
            useCartStore.setState({ ...cartResetState, isCartEmpty: true });
          } else {
            useCartStore.setState({
              cartItems: events.data.items,
              cartCosting: events.data.costing,
              cartItemCount: events.data.itemCount,
              cartSuggestions: events.data.cartSuggestions,
              showGoToCart: events.data.showGoToCart,
              isCartEmpty: false,
            });
          }
        }
      };
    
      return (
        <>
          {/* <ContentLoader /> */}
    
          <WebView
            source={{ uri: webViewURI }}
            style={{ flex: 1, backgroundColor: '#fff', marginBottom: Platform.OS === 'ios' ? 0 : 60, ...style }}
            ref={baseRef}
            // new addon
            // automaticallyAdjustsScrollIndicatorInsets={true}
            allowsBackForwardNavigationGestures={false}
            pullToRefreshEnabled={true}
            cacheEnabled={false} // read
            showsHorizontalScrollIndicator={false}
            showsVerticalScrollIndicator={false}
            // scalesPageToFit={Platform.OS == 'android' ? false : true} // experiment
            onScroll={onScrollHandler ? (e) => onScrollHandler(e.nativeEvent) : () => {}} // experiment
            originWhitelist={['*']}
            startInLoadingState={true}
            // injectedJavaScript={`
            //   window.platformInfo = ${Platform.OS === 'ios' ? "'ios'" : "'android'"};
            //   const consoleLog = (type, log) => window.ReactNativeWebView.postMessage(JSON.stringify({'type': 'Console', 'data': {'type': type, 'log': log}}));
            //   console = {
            //       log: (log) => consoleLog('log', log),
            //       debug: (log) => consoleLog('debug', log),
            //       info: (log) => consoleLog('info', log),
            //       warn: (log) => consoleLog('warn', log),
            //       error: (log) => consoleLog('error', log),
            //   };
            //   true;
            // `}
            javaScriptEnabled={true}
            sharedCookiesEnabled={true}
            thirdPartyCookiesEnabled={true}
            domStorageEnabled={true}
            renderError={(e) => console.log('Webview Render Error', e)}
            onShouldStartLoadWithRequest={handleNavigationChange}
            onMessage={(e) => webPostMessageHandler(e)}
            onLoadProgress={() => {
              baseRef.current.injectJavaScript(`
                window.platformInfo = ${Platform.OS === 'ios' ? "'ios'" : "'android'"};
                true;
              `);
              //   web_ref.current.injectJavaScript(`
              //   window.platformInfo = ${Platform.OS === 'ios' ? "'ios'" : "'android'"};
              //   const consoleLog = (type, log) => window.ReactNativeWebView.postMessage(JSON.stringify({'type': 'Console', 'data': {'type': type, 'log': log}}));
              //   console = {
              //       log: (log) => consoleLog('log', log),
              //       debug: (log) => consoleLog('debug', log),
              //       info: (log) => consoleLog('info', log),
              //       warn: (log) => consoleLog('warn', log),
              //       error: (log) => consoleLog('error', log),
              //   };
              //   true;
              // `);
              // setLoading(true);
            }}
            // onLoadEnd={() => setLoading(false)}
            onLoadStart={() => setLoading(true)}
            onLoad={() => {
              handleWebViewLoadStart(baseRef);
            }}
            renderLoading={() => <ContentLoader />}
            decelerationRate={0.998}
            allowsInlineMediaPlayback={true}
            allowsFullscreenVideo={false}
          />
        </>
      );
    };
    
    export default WebviewWrapper;
    
  5. nat-gaurav-saini commented on Jan 31, 2025

    @nat-gaurav-saini
    Author

    Hi @birdofpreyru
    I need to take app live on play store soon so would be helpful if you can take a look at this. Thanks!

  6. birdofpreyru commented on Jan 31, 2025

    @birdofpreyru
    Owner

    I need to take app live on play store soon so would be helpful if you can take a look at this. Thanks!

    I'll hardly look into it any time soon — it is irrelevant to my ongoing commercial projects; it does not have the highest priority for my personal hobby projects; and so far I make no otherwise profit from maintaining this library ¯\_(ツ)_/¯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P1

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions