Calling JavaScript Function from Android and Handling Result

In this tutorial I am going to describe JavaScriptInterface  for Calling Android Function from JavaScript i.e., JavaScript Binding to Android.

Setting up WebView
First add JavaScriptInterface to webView as follows. Here "MyAndroid" will be used later to call functions in JavaScriptInterface later.

  webView = (WebView) findViewById(;
  WebSettings webSettings = webView.getSettings();
  webView.addJavascriptInterface(new JavaScriptInterface(this), "MyAndroid");

The JavaScriptInterface Class:

 public class JavaScriptInterface {
     Context mContext;
     JavaScriptInterface(Context c) {
         mContext = c;
     //add other interface methods to be called from JavaScript

HTML File:
    <script type="text/javascript">
    function getValue(){
       //return value to Android 
       var val= document.ipForm.userName.value;
  <body >
    <form name="ipForm" id="ipForm">
      UserName : <input type="text" name="userName">
      <button type="button" onclick="getValue();">Submit</button>

Android part :

The main things to do on Android Code are :

a)Add a Button to Android UI and add onClickListener to it. We will call JavaScript's   getValue() method on onClick event of this Button.
callBtn = (Button) findViewById(;
callBtn.setOnClickListener(new OnClickListener() {
     public void onClick(View v) {
          //this calls javascript function

b)Adding Callback function in JavaScriptInterface for MyAndroid.receiveValueFromJs(val):
The value from webpage is contained in variable str which comes as parameter. 
public void receiveValueFromJs(String str) {
//do something useful with str
  Toast.makeText(mContext, "Received Value from JS: " + str,Toast.LENGTH_SHORT).show();

Note : Here, The function getValue() is called from both onClick event of android Button and onclick event of html submit button.

In summary, we did the following:

  • First we  registered the interfaces
  • JavaScript function-javascript:getValue() is called on onClick
  • getValue reads the value from form and returns to android by calling the callback function receiveValueFromJs. Here the value is send as parameter.