Sunday, March 11, 2012

Injecting a javascript for getting html of a webpage in Android

To get the source code of html page, we can use javascript . For this first we have to enable the javascript interface of the web view. Then provide a custom webview client for that view. We will get a onPage finished call after loading a url. And in this method we can inject a javascript to get a html. An example below

WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setSavePassword(false);
webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
webview.setWebViewClient(new WebViewClient() {
 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
  view.loadUrl(url);
  return true;
 }
 public void onPageFinished(WebView view, String url) {
  Log.i("Web view", "Finished loading URL: " + url);
//  killProgressDialog();
  webview.loadUrl("javascript:window.HTMLOUT.showHTML(document.getElementById('oauth_pin').innerHTML)");
 }

 @Override
 public void onPageStarted(WebView view, String url, Bitmap favicon) {
//  showProgressDialog();
  super.onPageStarted(view, url, favicon);
 }
 @Override
 public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//  killProgressDialog();
  Toast.makeText(getBaseContext(),"Loading error", Toast.LENGTH_SHORT).show();
 }
});


class MyJavaScriptInterface {
 public void showHTML(String html) {
                Log.i("HTML" ,html);                         
        }
}

No comments:

Post a Comment