Skip to content Skip to sidebar Skip to footer

How To Communicate Between WebView & JavaScript?

I am developing native application. My application have a WebView. I want to log this WebView's component's every action. Which button clicked, which image dragged. After that, I w

Solution 1:

You should add javascript interface to your webView like that:

webView.addJavascriptInterface(new JavascriptInterface(this), "AndroidFunction");

You should create interface class:

public class JavascriptInterface{
Context mContext;

    JavascriptInterface(Context c) {
        mContext = c;
    }

    public void save(String action){
        // save to database
    }
}

On the website you should call:

AndroidFunction.save("actionName");

Solution 2:

official link :http://developer.android.com/reference/android/webkit/WebView.html

 class JsObject {
        @JavascriptInterface
        public String toString() { return "injectedObject"; }
 }
 webView.addJavascriptInterface(new JsObject(), "injectedObject");
 webView.loadData("", "text/html", null);
 webView.loadUrl("javascript:alert(injectedObject.toString())");

------------------------------- MUST API>17

my tune up, HTML, jsobj.html:

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
                <title>Hello TEST JS</title>
            </head>

            <body style="background: white; font-family: Helvetica">

                <script type="text/javascript">
                document.write(AndroidFunction.show());
                AndroidFunction.save("abc");
                </script>
            </html>

Android:

web.addJavascriptInterface(new JsObject(), "AndroidFunction");

           ...

     class JsObject{
         @JavascriptInterface           
         public void save(String action){
             L.d("action:"+action);
         }

          public String show(){
                 return "Hello Android";
             }
     }      

Solution 3:

Have you ever take a look on PhoneGap and Cordova Plugin ? Cordova Plugin provides really strong communication between Java to webview and webview to Java. And there are already some open source plugins written about logging the data, you can just embed into your application.

Take a look on this link : Cordova Plugin


Post a Comment for "How To Communicate Between WebView & JavaScript?"