Android Calling JavaScript functions in WebView

前端 未结 7 602
夕颜
夕颜 2020-11-22 04:14

I am trying to call some javascript functions sitting in an html page running inside an android webview. Pretty simple what the code

7条回答
  •  无人及你
    2020-11-22 04:54

    I created a nice wrapper to call JavaScript methods; it also shows JavaScript errors in log:

    private void callJavaScript(String methodName, Object...params){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("javascript:try{");
        stringBuilder.append(methodName);
        stringBuilder.append("(");
        for (int i = 0; i < params.length; i++) {
            Object param = params[i];
            if(param instanceof String){
                stringBuilder.append("'");
                stringBuilder.append(param.toString().replace("'", "\\'"));
                stringBuilder.append("'");
            }
            if(i < params.length - 1){
                stringBuilder.append(",");
            }
        }
        stringBuilder.append(")}catch(error){Android.onError(error.message);}");
        webView.loadUrl(stringBuilder.toString());
    }
    

    You need to add this too:

    private class WebViewInterface{
    
        @JavascriptInterface
        public void onError(String error){
            throw new Error(error);
        }
    }
    

    And add this interface to your webview:

    webView.getSettings().setJavaScriptEnabled(true);
    webView.addJavascriptInterface(new WebViewInterface(), "AndroidErrorReporter");
    

提交回复
热议问题