Search code examples
javascriptreact-nativewebview

How to reinject JavaScript when a react-native-webview reloads?


To work properly, we need to inject certain functions into a webview we integrated in our React Native App. If the webview reloads, the javascript needs to be re-injected accordingly. How is this possible?

The javascript should be injected into the webview not only until the webview reloads.


Solution

  • The main idea is to use injectJavaScript on page load.

    const App = () => {
      const webViewRef = React.useRef<WebView>(null);
      const reloadsCount = React.useRef<number>(0);
      const onLoadInjected = `
        window.addEventListener('load', (event) => {
          window.ReactNativeWebView.postMessage('InjectNewCode');
        });
      `;
    
      const injectNewJsCode = () => {
        webViewRef.current?.injectJavaScript(`alert('new code injected')`)
        reloadsCount.current++
      }
    
      return (
        <WebView
          ref={ webViewRef }
          pullToRefreshEnabled={ true }
          source={{
            uri: 'https://stackoverflow.com/questions/74386954/how-to-reinject-javascript-when-a-react-native-webview-reloads',
          }}
          onMessage={ ({ nativeEvent }) => {
            if (nativeEvent.data === 'InjectNewCode') {
              // skip the inital load event
              if (reloadsCount.current > 0) {
                injectNewJsCode()
              }
              reloadsCount.current++
            }
          }}
          injectedJavaScript={ onLoadInjected }
        />
      );
    };