3

I'm working on a React Native app that uses a WebView as the app's main screen.

When the app comes from the background to the foreground the WebView reloads. How can I stop this reloading?

This answer suggests loading the WebView in ViewDidLoad() rather than in ViewDidAppear() or ViewWillAppear(). Is this a real solution and how can I confirm, or change, how the WebView is loaded by React Native?

As a hacky solution I'm using onNavigationStateChange to save the current URL in AsyncStorage and then load this URL when the app comes to the foreground. This solution isn't great because it:

  1. Breaks the browser history, affecting javascript back buttons
  2. Doesn't remember form state
  3. Might send the user to a page they can't directly access, resulting in them being sent to a 404

So I'd much prefer a solution that stops the reloading, at least for situations when the app is only momentarily in the background.

matthew
  • 2,156
  • 5
  • 22
  • 38
  • 1
    I think the Webview isn't meant to reload when coming to foreground. In my RN app we use WKWebView and the pages stay loaded when coming from background. Maybe your state changes when the app awakes and this causes the component that contains the WebView to rerender. You can try adding a should ComponentUpdate to make sure the WebView re-renders only when needed. – needsleep Nov 07 '18 at 18:15
  • 1
    Thanks @needsleep you are correct. My issue was caused by a React Navigation SwitchNavigator, which "resets routes to their default state when you switch away". This reset caused the WebView to reload. – matthew Nov 09 '18 at 19:12

1 Answers1

1

This was not and issue with the WebView. The reloading was caused by my misuse of the React Navigation SwitchNavigator. As mentioned in the docs a SwitchNavigator

resets routes to their default state when you switch away

This reset caused the WebView to reload.

matthew
  • 2,156
  • 5
  • 22
  • 38