版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zsp_android_com/article/details/85234792
资料
最全面总结Android WebView与JS交互方式
Android混合开发(一)
安卓混合开发-原生Java和H5交互,保证一看就懂!
概览
Java调js
详述
- 通WebView之loadUrl()
- HTML
function returnResult(result){ alert("result is" + result); }
- Java
调用
调试、拦截webView.setWebViewClient(new WebViewClient() { // 开始加载 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); progressBar.setVisibility(View.VISIBLE); } // 加载完成 @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressBar.setVisibility(View.GONE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // 4.4及以上 view.evaluateJavascript("javascript:returnResult('测试一')", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { Log.e("js返", value); } }); } else { // 常量 view.loadUrl("javascript:returnResult('测试二')"); // 变量(需转义) /*String s = "test"; view.loadUrl("javascript:alertMessage(\" " + s + "\")");*/ } } });
webView.setWebChromeClient(new WebChromeClient() { @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); setToolbarTitle(title); } // 加载度 @Override public void onProgressChanged(WebView view, int newProgress) { } /** * Report a JavaScript console message to the host application. The ChromeClient * should override this to process the log message as they see fit. * @param consoleMessage Object containing details of the console message. * @return true if the message is handled by the client. */ @Override public boolean onConsoleMessage(ConsoleMessage consoleMessage) { Log.e("调试", consoleMessage.message()); return true; } /** * Tell the client to display a javascript alert dialog. If the client * returns true, WebView will assume that the client will handle the * dialog. If the client returns false, it will continue execution. * * @param view The WebView that initiated the callback. * @param url The url of the page requesting the dialog. * @param message Message to be displayed in the window. * @param result A JsResult to confirm that the user hit enter. * @return boolean Whether the client will handle the alert dialog. */ @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.e("onJsAlert", result.toString()); return super.onJsAlert(view, url, message, result); } });
- HTML
- 通过WebView之evaluateJavascript()
参考上
对比
js调Java
- 通WebView之addJavascriptInterface()对象映射
- 通WebViewClient之shouldOverrideUrlLoading()回调拦截url
- 通WebChromeClient之onJsAlert()、onJsConfirm()、onJsPrompt()回调拦截js对话框alert()、confirm()、prompt()消息
注意
- 本地/远程加载均可。
- Java同js交互。所调法需HTML中,非HTML中或js中(HTML引js)均无效。
- WebChromeClient之onJsAlert中不可返true,否有弹窗但看不见致页面假死。
@Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { LogUtils.e("onJsAlert", url + message + result); return super.onJsAlert(view, url, message, result); }