Android JavaScriptInterface在Android GINGERBREAD中没有调用方法

时间:2014-02-20 11:46:52

标签: android android-webview bind android-2.3-gingerbread

我在WebView中注入了一些JavaScript,以便检测按钮点击。它在我测试它的所有设备中都能正常工作,但GINGERBREAD设备除外。在那个设备中,我收到了这个错误:

Uncaught TypeError: Object com.zonaapp.flamencomovil.PromotionActivity$1@407c3088 has no method 'share' at :1

这是我的相关代码:

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);
}

这是我的分享方法:

@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);
}

在所有其他操作系统版本中正确调用了方法!

1 个答案:

答案 0 :(得分:0)

您应该在JSInterface类

中定义您的share()方法

以下是解决方案:

    //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);
    }
}