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(R.id.webView);
  WebSettings webSettings = webView.getSettings();
  webSettings.setJavaScriptEnabled(true);
  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:
<html>
  <head>
    <script type="text/javascript">
    function getValue(){
       //return value to Android 
       var val= document.ipForm.userName.value;
       MyAndroid.receiveValueFromJs(val);
    }
    </script>
    <title></title>
  </head>
  <body >
    <form name="ipForm" id="ipForm">
      UserName : <input type="text" name="userName">
      <button type="button" onclick="getValue();">Submit</button>
    </form>
  </body>
</html>

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(R.id.callBtn);
callBtn.setOnClickListener(new OnClickListener() {
    @Override
     public void onClick(View v) {
          //this calls javascript function
          webView.loadUrl("javascript:getValue()");
    }
});


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.