How can I call a native function from cordova/phonegap webview for example for showing an ad.
EDIT: OK I FUNALLY GOT IT and I'm gonna write some steps for all of you who don't know how to do that (just to spare 2 days of your lifetime :D)
A) if you have just cordova/phonegap and and wish to call from js do this:
1) Replace the following code with your existing DroidGap Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init(); // Calling this is necessary to make this work
appView.addJavascriptInterface(this, "MainActivity");
/* "this" points the to the object of the current activity. "MainActivity" is used to refer "this" object in JavaScript as in Step 3. */
super.loadUrl("file:///android_asset/www/index.html");
}
2) Add the custom function in current (this) activity as following.
@JavascriptInterface
public void customFunctionCalled() {
Log.e("Custom Function Called", "Custom Function Called");
}
3) Now call this function from your HTML/JavaScript code as following.
window.MainActivity.customFunctionCalled();
B.1) if you have cordova/phonegap implemented in a webview and wish to call from js do this: (and want to call normal function)
1) Add this to the main java file:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
2) Declare the class JavaScriptInterface:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
@JavascriptInterface
public void showLog(){
Log.v("blah", "blah blah");
}
}
3) Call it from js with `window.JSInterface.showLog();
B.2) if you have cordova/phonegap implemented in a webview and wish to call from js (and want to call UI function, like a toast) do this:
1) Add this to the main java file:
JavaScriptInterface jsInterface = new JavaScriptInterface(this);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(jsInterface, "JSInterface");
2) Declare the class JavaScriptInterface:
public class JavaScriptInterface {
private Activity activity;
public JavaScriptInterface(Activity activiy) {
this.activity = activiy;
}
@JavascriptInterface
public void myFunction()
{
activity.runOnUiThread(new Runnable() {
public void run() {
//Code that interact with UI
showToast();
}
});
}
}
3) Add the toast function underneath:
public void showToast(){
Toast.makeText(getApplicationContext(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
}
4) Call it with `window.JSInterface.myFunction();
As you see if you need a function that uses the UI you need to wrap your function into activity.runOnUiThread so that it can get called from js.
*If you want to call from java a jquery method do this:
Java:
cordova_webview.loadUrl("javascript:window.functionn()");
Javascript:
window.function = punish;
Have a nice day!