Sunday, 31 July 2011

Using Java script in Android WebView through JSInterface

This is a very powerful way to implement java script into Android web view component using JavascriptInterface. You can easily invoke an android method from a WebView.

Let say :

There is a WebView ....
WebView web = new WebView();

Now we need to make it js enabled ...
WebSettings settings = web.getSettings();
settings.setJavaScriptEnabled(true);

Now , need to point it to our custom JSInterface class ..
web.addJavascriptInterface(new JSInterface(), "jsinterface");

Now, load a custom html to load ...

String html = new String();
html = ("<html><center><img border=\"0\" onClick=\"window.jsinterface.specialClick('" + parameter_1 + "','" + parameter_2 + "');\" " + " width='60dip' src=\"" + mediaSource + "\"></html>");
web.loadData(html, "text/html", "utf-8");

This html will load a image fetching from either a url or file ( mediaSource ) and we want to track the onClick method of WebView in the Android code itself. So, there is a method in the JSInterface called specialClick() which will do it. And to invoke the method into HTML code , use the code ..

onClick="window.jsinterface.specialClick('" + parameter_1 + "','" + parameter_2 + "');

Now, the time to write the JSInterface class and specialClick() method.

Create a class named JSInterface and put the code ...


public class JSInterface
{
public void specialClick(String param1, String param2)
{
Log.d("CZ","param1..." + param1 + " , param2..." + param2);
handler.post(new Runnable()
{
public void run()
{
}
});
}
}


In such way , whatever parameters you have passed from HTML onClick method , you will get it in Android code. So, connection between WebView javascript and Android native code is done.

For, further clarification and doubts , you may contact me ....  surojit.pakira@collectivezen.com




14 comments:

  1. Hi Surojit,
    thank you for your example.
    Could you please post here the working code?

    Then (not related to your example) did you happen to try to do some string manipulation in a JavaScript? (on Android)
    I couldn't split a string in JS, nor even look for a substring inside the JS method. I was thinking that you have experience with that as well

    Thanks a lot,
    Cristian

    ReplyDelete
  2. Hello Cristian,

    Thanks a lot for the comment !!!
    Yeah , I will post a working code over here soon.

    For your last question , could you please elaborate the question ? If you do so, then I might help you in that matter !!

    Regards,
    Surojit

    ReplyDelete
  3. Hi there, thanks for the code but I believe js method should not have window in the end. So it should be
    jsinterface.method()
    not
    window.jsinterface_method()

    Thanks
    (reference http://developer.android.com/guide/webapps/webview.html#BindingJavaScript)

    ReplyDelete