Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How I get page source from WebView?

How I get the web page's source from WebView?

I want to only enter www.google.com in my webview and When I entered this site, I want to get the source for example

String a=........;(source) 
like image 437
Ersin Gülbahar Avatar asked Apr 01 '12 17:04

Ersin Gülbahar


People also ask

How get HTML data from WebView?

HTML, CSS and JavaScript for Android WebView Depending on your requirements, you can fetch the contents of the WebView from the web using webView. loadUrl("<url>") method, or you can bind the code directly (e.g. after loading it from assets) using webView. loadDataWithBaseURL("", html, "text/html", "UTF-8", null) .

Is WebView open source?

Since Android 4.4 (KitKat), the WebView component is based on the Chromium open source project. WebViews now include an updated version of the V8 JavaScript engine and support for modern web standards previously missing in old WebViews.


1 Answers

I am not sure how far this is going to be helpful. But I have used the below snippet to fetch a small html page's data. I hope it helps you.

Create a class like the one below,

  class MyJavaScriptInterface
  {
      @SuppressWarnings("unused")
      public void processHTML(final String html)
      {
          Log.i("processed html",html);

            Thread OauthFetcher=new Thread(new Runnable() { 

                @Override
                public void run() {

                    String oAuthDetails=null;
                      oAuthDetails=Html.fromHtml(html).toString();
                      Log.i("oAuthDetails",oAuthDetails);

                }
            });OauthFetcher.start();
        }
      } 

Now in your onCreate(),

 webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

     webview.setWebViewClient(new WebViewClient(){

            @Override
            public void onPageFinished(WebView view, final String url) {


                String oAuthUrl=getString("www.google.com");

                if(url.contains(oAuthUrl))
                {
                    Log.i("Contains","Auth URL");

                    twitter_webview.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
                }
            }
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                progressDialog.show();
            }
      });

And now what happens is that, when your page finishes loading, the JavaScript class will be called, which would retrieve the page source and store it in a String as your requirement.

like image 177
Andro Selva Avatar answered Sep 28 '22 08:09

Andro Selva