webview与js交互

mWebView =(WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); // 设置与Js交互的权限 webSettings.setJavaScriptEnabled( true ); // 设置允许JS弹窗 webSettings.setJavaScriptCanOpenWindowsAutomatically( true ); // 先载入JS代码 // 格式规定为:file:///android_asset/文件名.html mWebView.loadUrl( "file:///android_asset/javascript.html" ); button = (Button) findViewById(R.id.button); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick (View v) { // 必须另开线程进行JS方法调用(否则无法调用) mWebView.post( new Runnable() { @Override public void run () { // 注意调用的JS方法名要对应上 // 调用javascript的callJS()方法 mWebView.loadUrl( "javascript:callJS()" ); } }); } }); // 由于设置了弹窗检验调用结果,所以需要支持js对话框 // webview只是载体,内容的渲染需要使用webviewChromClient类去实现 // 通过设置WebChromeClient对象处理JavaScript的对话框 //设置响应js 的Alert()函数 mWebView.setWebChromeClient( new WebChromeClient() { @Override public boolean onJsAlert (WebView view, String url, String message, final JsResult result) { AlertDialog.Builder b = new AlertDialog.Builder(MainActivity. this ); b.setTitle( "Alert" ); b.setMessage(message); b.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick (DialogInterface dialog, int which) { result.confirm(); } }); b.setCancelable( false ); b.create().show(); return true ; } });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值