Android Calling JavaScript functions in WebView

前端 未结 7 692
夕颜
夕颜 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 05:04

    Modification of @Ilya_Gazman answer

        private void callJavaScript(WebView view, String methodName, Object...params){
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("javascript:try{");
            stringBuilder.append(methodName);
            stringBuilder.append("(");
            String separator = "";
            for (Object param : params) {               
                stringBuilder.append(separator);
                separator = ",";
                if(param instanceof String){
                    stringBuilder.append("'");
                }
                    stringBuilder.append(param.toString().replace("'", "\\'"));
                if(param instanceof String){
                    stringBuilder.append("'");
                }
    
            }
            stringBuilder.append(")}catch(error){console.error(error.message);}");
            final String call = stringBuilder.toString();
            Log.i(TAG, "callJavaScript: call="+call);
    
    
            view.loadUrl(call);
        }
    

    will correctly create JS calls e.g.

    callJavaScript(mBrowser, "alert", "abc", "def");
    //javascript:try{alert('abc','def')}catch(error){console.error(error.message);}
    callJavaScript(mBrowser, "alert", 1, true, "abc");
    //javascript:try{alert(1,true,'abc')}catch(error){console.error(error.message);}
    

    Note that objects will not be passed correctly - but you can serialize them before passing as an argument.

    Also I've changed where the error goes, I've diverted it to the console log which can be listened by:

        webView.setWebChromeClient(new CustomWebChromeClient());
    

    and client

    class CustomWebChromeClient extends WebChromeClient {
        private static final String TAG = "CustomWebChromeClient";
    
        @Override
        public boolean onConsoleMessage(ConsoleMessage cm) {
            Log.d(TAG, String.format("%s @ %d: %s", cm.message(),
                    cm.lineNumber(), cm.sourceId()));
            return true;
        }
    }
    

提交回复
热议问题