webview与js交互两种方式

安卓里面经常会用到webview与js交互的问题,一般有两种方式处理
1.通过与web方面定义接口方式:(推荐
安卓端代码实现:

       JavaScriptInterface JSInterface;
        wv = (WebView) findViewById(R.id.web);
        wv.getSettings().setJavaScriptEnabled(true); ///------- 设置javascript 可用
        JSInterface = new JavaScriptInterface(this); // 实例化接口对象
        wv.addJavascriptInterface(JSInterface, "DzhInterface"); // 设置js接口  第一个参数事件接口实例,第二个是实例在js中的别名,这个在js中会用到
        wv.setWebChromeClient(new WebChromeClient() {//允许有alert弹出框
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
            }
            /**
             * 处理alert弹出框,拦截web端弹框由android原生处理
             */
            @Override
            public boolean onJsAlert(WebView view, String url,
                                     final String message, JsResult result) {
                Log.d("return","onJsAlert:"+message);
			   //对alert的简单封装
				new AlertDialog.Builder(TestActivity.this).
					setTitle("Alert").setMessage(message).setPositiveButton("OK",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface arg0, int arg1) {
						   //TODO
					   }
				}).create().show();
                result.confirm();
                return  true;
            }
            /**
             * 处理confirm弹出框
             */
            @Override
            public boolean onJsConfirm(WebView view, String url, String message,
                                       JsResult result) {
                result.confirm();
                return true;
                //如果采用下面的代码会另外再弹出个消息框
                //return super.onJsConfirm(view, url, message, result);
            }
            /**
             * 处理prompt弹出框
             */
            @Override
            public boolean onJsPrompt(WebView view, String url, String message,
                                      String defaultValue, JsPromptResult result) {
                result.confirm();
                return super.onJsPrompt(view, url, message, message, result);
            }

        });
        wv.setWebViewClient(new MyWebViewClient(){//解决部分机型打开Url会提示使用外部浏览器
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        
//自定义接口
 public class JavaScriptInterface {
        String returnParam;
        Context mContext;
        JavaScriptInterface(Context c) {
            mContext = c;
        }
        @JavascriptInterface
        public void getAccount(final String intoParm){//web传过来的参数
            TestActivity.this.runOnUiThread(new Runnable() {//与界面交互的要在主线程中实现
                @Override
                public void run() {
                    new AlertDialog.Builder(TestActivity.this).
                            setTitle("Alert").setMessage(intoParm).setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    //TODO
                                    wv.loadUrl(String.format("javascript:onLoginResult('%s')", returnParam));//returnParam传给web的参数
                                }
                            }).create().show();
                }
            });
        }
    }

web端实现:


Android与JS互调示例

JS调用Android原生功能

||

Android调用JS

登录结果:

2.通过伪链接方式实现js与安卓原生交互,此种方式较简单但是扩展性容易受到影响,定义关键字越来越多,容易出现被提前截断。(慎用!)

setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 捕获网址,以后也许可以根据锚链接处理点互动
                if(url.contains("HELLO WORLD")){//通过捕获地址包含此关键字就走安卓原生,否则就不做处理直接加载该网址。
                  Intent intent = new Intent(mContext,SecondActivity.class);
                  startActivity(intent);
				  return true;
				}else{
				 view.loadUrl(url);
				}
                return true;
            }
			@Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                        super.onPageStarted(view,url,favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
     					super.onPageFinished(view,url);
            }

			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				super.onReceivedError(view, errorCode, description, failingUrl);
			}

			@Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            super.onReceivedSslError(view,handler,error);
            }
        });

你可能感兴趣的:(android,网页交互)