3

So I've got a React-Typescript webapp that I am hosting in a WebView in my Android app.

I'm simply trying to pass data from the Android client to the Webview. However the fact that It's a React app that builds with webpack seems to complicated things.

Following the instructions found from this stack response: Passing data from java class to Web View html

I tried to add a function in the Index.tsx and call that from andoird like this:

webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("file:///android_asset/test.html");
webview.setWebViewClient(new WebViewClient(){
    public void onPageFinished(WebView view, String url){   
        webview.loadUrl("javascript:init('" + theArgumentYouWantToPass + "')");
    }           
});

However it could not find the function. My next thought was to just add it to the Index.Html, however I would then need to store the data in some way that I could reference it from my React code.

I tried using Local Storage like this:

    <script type="text/javascript">
        function init(val)
        {
            window.localStorage.setItem("key", val);
        }
    </script>

I tried this with and w/o the window prefix but both times it gives me an error saying I'm trying to call setItem on a null reference.

Does anybody know how I can send data from Android to my React app?

Brian C
  • 111
  • 8

1 Answers1

1

You need to enable localStorage in the settings (similar to setJavaScriptEnabled) e.g.

webview.getSettings().setDomStorageEnabled(true);
basarat
  • 261,912
  • 58
  • 460
  • 511