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:
publicclassJavascriptInterface{
Context mContext;
JavascriptInterface(Context c) {
mContext = c;
}
publicvoidsave(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
classJsObject {
@JavascriptInterfacepublicStringtoString() { return"injectedObject"; }
}
webView.addJavascriptInterface(newJsObject(), "injectedObject");
webView.loadData("", "text/html", null);
webView.loadUrl("javascript:alert(injectedObject.toString())");
------------------------------- MUST API>17
my tune up, HTML, jsobj.html:
<!DOCTYPE htmlPUBLIC"-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xml:lang="en"lang="en"><head><metahttp-equiv="Content-Type"content="text/html; charset=UTF-8" /><title>Hello TEST JS</title></head><bodystyle="background: white; font-family: Helvetica"><scripttype="text/javascript">document.write(AndroidFunction.show());
AndroidFunction.save("abc");
</script></html>
Android:
web.addJavascriptInterface(newJsObject(), "AndroidFunction");
...
classJsObject{
@JavascriptInterfacepublicvoidsave(String action){
L.d("action:"+action);
}
publicStringshow(){
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?"