Html文件:
WebView与JS交互方式:
1. 前提:
WebSettings webSettings = webView.getSettings();
// 设置与Js交互的权限
webSettings.setJavaScriptEnabled(true);webView.setWebChromeClient(new WebChromeClient(){@Overridepublic boolean onJsAlert(WebView view, String url, String message, JsResult result) {AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this).setTitle(R.string.app_name).setMessage(message).setPositiveButton("ok", new AlertDialog.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {result.confirm();}});b2.setCancelable(false);b2.create();b2.show();return true;}
});
JS的弹框在WebView中需要通过重写onJsAlert()、onJsConfirm()、onJsPrompt()方法实现,分别对应JS的警告框,确认框,输入框。
webView还有一个setWebClient()方法,帮助处理各种通知、请求事件。
setWebChromeClient辅助WebView处理JavaScript的对话框,网站图标,网站title,加载进度等
2. WebView调用JS的方法
(1) 通过WebView的loadUrl()
加载对应页面
webView.loadUrl("file:/sdcard/WebView_Test.html");
webView.loadUrl("https://www.baidu.com/");
调用JS中的callJS()方法
webView.loadUrl("javascript:callJS()");
(2) 通过WebView的evaluateJavascript()
webView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {@Overridepublic void onReceiveValue(String value) {//此处为 js 返回的结果}
});
3. JS中调用Android方法
通过addJavascriptInterface()进行对象映射
public class JniUtil {static {System.loadLibrary("native_text");}@JavascriptInterfacepublic static native String helloWorld();@JavascriptInterfacepublic void hello(String msg) {System.out.println("JS调用了Android的hello方法");}
}webView.addJavascriptInterface(new JniUtil(), "test");
test是JniUtil对象,可以在JS中使用,在JS中调用test.hello()或者test.helloWorld()都可以看到对应结果,注意方法要加上对应注解。
安卓webView显示pdf方法