Access the JSON response from webview of android

19,368

Build a class called MyJavaScriptInterface. And MyJavaScriptInterface to WebView.

    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://pqrs.abcde.com/facebook");
    wb.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

    class MyJavaScriptInterface {

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

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

}

Note: From you are required to remove window in wb.loadUrl("javascript:...");. And @JavascriptInterface before "public void showHTML".

You can get content from showHtml(..) in html parameter.

Share:
19,368
Admin
Author by

Admin

Updated on July 24, 2022

Comments

  • Admin
    Admin almost 2 years

    On Android, I have a webView. I'm loading a url on it. Firstly, I get a login page of Facebook and after filling login details it gives me a JSON Response on same webView.

    I'm using this code to load that URL but now I don't know how to get that JSON Response in a string what I got on finished of that url.

    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:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
        }
    };
    wb = (WebView) findViewById(R.id.webview);
    wb.getSettings().setJavaScriptEnabled(true);
    wb.getSettings().setSupportZoom(true);
    wb.getSettings().setBuiltInZoomControls(true);
    wb.setWebViewClient(yourWebClient);
    wb.loadUrl("http://pqrs.abcde.com/facebook");
    

    The format of JSON Response is:

    {"status":"success","msg":"You have successfully logged in."}