I want to create a plugin for phone which pass and returns the value between javascript and android.
Can anybody suggest any ideas on how to do this?
Actually, this is not very difficult. Here, I will show you how to call native code from javascript within the page and vice-versa:
Calling native code from within web view:
When creating the web view add javascript interface (basically java class whose methods will be exposed to be called via javascript in the web view.
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
The definition of the javascript interface class itself (this is exemplary class I took from another answer of mine and opens video in native intent)
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
public void startVideo(String videoAddress){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(videoAddress), "video/3gpp"); // The Mime type can actually be determined from the file
activity.startActivity(intent);
}
}
Now if you want to call this code form the HTML of the page you provide the following method:
<script>
function playVideo(video){
window.JSInterface.startVideo(video);
}
</script>
Easy isn't it?
Calling javascript code from native code:
This is also simple suppose in the code of the HTML loaded in WebView you have javascript function defined:
<script>
function function(){
//... do something
}
</script>
Then you call this function through the WebView in the native code like that:
webView.loadUrl("javascript:function()");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With