Wednesday, June 5, 2013

Android Webview tricks to get alert and console.log() messages.

There are many tutorials to write a webview so i am not covering the ways to create a webview instead  i wanted to show how we can get the javascript consol.log('test'), and alert('message') from WebChromeClient api  which can be used to debug hybrid application.




private class SampleWebChromeClient extends WebChromeClient {

@Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
   Log.d("SampleActivity", consoleMessage.message() + " -- From line "
            + consoleMessage.lineNumber() + " of "
            + consoleMessage.sourceId() );

   return true;
}

@Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
  Log.d("SampleActivity", message);
        //new AlertDialog.Builder(view.getContext()).setMessage(message).setCancelable(true).show();
  Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
        result.confirm();
        return true;
}

}


For KitKat > using the below code and you can debug inside the web view. For more details refer here.

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
      WebView.setWebContentsDebuggingEnabled(true);
  }

2 comments:

  1. I hope you will share such type of impressive contents again with us so that we can utilize it and get more advantage.

    Android App Developer in Pakistan

    ReplyDelete