How to make a communication bridge between WebView to Native Android App

Viewed 319

On Android, I have a webView. I'm loading a url of one react JS App. By clicking on some button in react App it will make an API call, which gives a JSON Response on the same webView.

I'm using this code to load that URL but now I don't know how to get that JSON Response back to the Native Android app in a string.

WebViewClient yourWebClient = new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            wb.loadUrl("javascript:HtmlViewer.showHTML" +
                    "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
        }
    };
    wb = (WebView) findViewById(R.id.webview);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.getSettings().setSupportZoom(true);
    wb.getSettings().setBuiltInZoomControls(true);
    wb.setWebViewClient(yourWebClient);
    wb.loadUrl("http://myreactappurl");
    wb.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

Helper class code:

class MyJavaScriptInterface {

    private Context ctx;
    MyJavaScriptInterface(Context ctx) {
        this.ctx = ctx;      
    }

    @JavascriptInterface
    public void showHTML(String html) {
        System.out.println(html);
    }

}

By using this code instead of getting JSON Response, i am getting Whole HTML code.

This is the sample JSON Response from API call.

{"status":"success","msg":"API Response"}

Can anyone please help me to solve this problem ?

0 Answers
Related