I am injecting some JavaScript inside a WebView in order to detect a button click. It's working correctly in all devices where I tested it except in GINGERBREAD devices. In that device I am getting this error:
Uncaught TypeError: Object com.zonaapp.flamencomovil.PromotionActivity$1@407c3088 has no method 'share' at :1
This is my relevant code:
private void startWebview(){
wvPromo.getSettings().setJavaScriptEnabled(true);
wvPromo.addJavascriptInterface(this, "JSInterface");
wvPromo.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
if(mDialog!=null && mDialog.isShowing()) mDialog.dismiss();
view.loadUrl("javascript:(function() { "
+ "var myEl = document.getElementById('boton_regalar'); "
+ "myEl.addEventListener('click', function(){window.JSInterface.share();}, false);"
+ "})();");
view.addJavascriptInterface(this, "JSInterface");
}
});
wvPromo.setWebChromeClient(new WebChromeClient() {
public void onConsoleMessage(String message, int lineNumber,
String sourceID) {
Log.d("MyApplication", message + " -- From line " + lineNumber
+ " of " + sourceID);
}
});
wvPromo.loadUrl(promo.getWebViewURl());
wvPromo.setBackgroundColor(0x00000000);
}
And here is my share method:
@JavascriptInterface
public void share() {
Log.i(getClass().getSimpleName(), "Share button");
String textShare = promo.getShareTitle() + " " + promo.getShareUrl();
Intent i = Utils.shareContentIntent(this,textShare, promo.getShareTitle());
startActivity(i);
}
Method is correctly called in all others OS versions!
You should define your share() method inside JSInterface class
Here's the solution:
//1) init your webView and set interface
void initWebView(){
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(this, "JSInterface");
}
//2) Wrap js function call into interface like so
void callJsFunction(){
webView.loadUrl("javascript:JSInterface.onShare( shareFunction(){} );");
}
//3) Define your interface class and catch the callback
class JSInterface{
@JavascriptInterface
public void onShare() {
//catch the callback
Log.i(getClass().getSimpleName(), "Share button");
String textShare = promo.getShareTitle() + " " + promo.getShareUrl();
Intent i = Utils.shareContentIntent(this,textShare, promo.getShareTitle());
startActivity(i);
}
}