Android JavaScriptInterface tutorial and example for calling JavaScript function from Android

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

I have written a blog post about : Calling JavaScript Function from Android and Handling Result

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
}

The Major Steps that should be followed are :
  • First Add a method in JavaScriptInterface Class , say myMethod
  • And call the method from Android as MyAndroid.myMethod(Params ...)from JavaScript, where MyAndroid is name of this JavaScriptInterface which is already set as :   webView.addJavascriptInterface(new JavaScriptInterface(this), "MyAndroid");

HTML File:

<html>
  <head>
    <script type="text/javascript">
    function sayHello(msg){
        //calls Android's JavaScriptInterface Function
        MyAndroid.showToast(msg);
    }
    </script>
  </head>
  <body >
    <div onclick="sayHello('hello')"> Click Me !!  </div>
  </body>
</html>

Android part:


Adding showToast(String) callback method in JavaScriptInterface

public void showToast(String msg) {
  Toast.makeText(mContext, "Received Msg :" + msg,Toast.LENGTH_SHORT).show();
}



No comments :

Post a Comment

Your Comment and Question will help to make this blog better...