Search code examples
reactjsreact-nativewebviewlocal-storageasyncstorage

How to Detect Local Storage Changes in react-native-webview for React Native App


I am developing a React Native app that incorporates a React application via react-native-webview. My goal is to synchronize changes made to the language key in the web view’s local storage with the async storage in my React Native app.

Here’s the current setup:

  1. React Native App: This is the main application.
  2. React App: Runs inside a react-native-webview in the React Native app.

I need to detect whenever the language key in the web view’s local storage changes, and subsequently update the async storage in the React Native app accordingly.

I attempted to periodically check for changes in the local storage by setting up intervals within the React native app (with injected JS). This approach does successfully detect changes, but I am aware that using intervals is not efficient or the most effective method for this purpose. I am looking for a more optimal approach.


Solution

  • Post a message from React app to native side when language changes.

    window.ReactNativeWebView.postMessage(JSON.stringify({language: "en"}))
    

    Then listen changes on native side.

    <WebView
    ...
      onMessage={(event) => {
        const data = JSON.parse(event.nativeEvent.data)
      }}
    />
    

    See doc for details.