美文网首页
WebView加载http、https细节,交互及注意事项

WebView加载http、https细节,交互及注意事项

作者: Batashi | 来源:发表于2018-06-13 17:01 被阅读0次

    一、源码:

    @SuppressLint("SetJavaScriptEnabled")
        public void initWebView() {
            webView.setWebViewClient(new CusWebViewClient());
            webView.setWebChromeClient(new CusWebChromeClient());
            WebSettings setting = webView.getSettings();
            setting.setJavaScriptEnabled(true);
            setting.setAllowFileAccess(true);
            String dir = getApplicationContext().getCacheDir().getAbsolutePath();
    
            setting.setDomStorageEnabled(true);// 开启 DOM storage API 功能
            setting.setGeolocationEnabled(true);
            setting.setUserAgentString("Mozilla/5.0 (Linux; Android 6.0.1; SM-G920V Build/MMB29K) AppleWebKit/537.36 " +
                    "(KHTML, like Gecko) Chrome/52.0.2743.98 Mobile Safari/537.36");
            setting.setRenderPriority(RenderPriority.HIGH);
            setting.setCacheMode(WebSettings.LOAD_DEFAULT); // 设置 缓存模式
            setting.setAppCachePath(dir);// 设置 Application Caches 缓存目录
            // 开启 Application Caches 功能
            setting.setAppCacheEnabled(true); // 开启 Application Caches 功能
            setting.setDefaultTextEncodingName("UTF-8");// 设置字符编码
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Log.v(TAG, "版本大于21,启动setMixedContentMode(0)");
                setting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); // 解决http及https混合情况下页面加载问题
            } else {
                Log.v(TAG, "版本小于21,无须启动setMixedContentMode(0)");
            }
            // 让网页适配手机
            setting.setUseWideViewPort(true);
            setting.setLoadWithOverviewMode(true);
            webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);// 滚动条风格,为0指滚动条不占用空间,直接覆盖在网页上
            webView.addJavascriptInterface(new Contact(), "contact");
            loadWeb(currentUrl);
        }
    
    private class CusWebViewClient extends WebViewClient {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {// 网页页面开始加载的时候
                if (WebActivity.this.isFinishing()) {
                    return;
                }
                Log.e(TAG, "--onPageStarted()--, url : " + url);
                showProgress("加载中");
                webView.setEnabled(false);// 当加载网页的时候将网页进行隐藏
                super.onPageStarted(view, url, favicon);
            }
    
            @Override
            public void onPageFinished(WebView view, String url) {// 网页加载结束的时候
                Log.e(TAG, "onPageFinished , url : " + url);
                hidProgress();
                webView.setEnabled(true);
                if (!mLoadError) {
                    webView.setVisibility(View.VISIBLE);
                    errorWebView.setVisibility(View.GONE);
                }
                super.onPageFinished(view, url);
            }
    
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) { // 网页加载时的连接的网址
                Log.d(TAG, "页面加载href:" + url);
                loadWeb(url);
                return true;
            }
    
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.e(TAG, "onReceivedError, errorCode : " + errorCode + ", failingUrl : " + failingUrl + ", description : " + description);
                if (failingUrl.equals(currentUrl)) {
                    loadFailtUrl();
                }
            }
    
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                String reqUrl = request.getUrl().toString();
                Log.e(TAG, "onReceivedHttpError, reqUrl : " + reqUrl + ", currentUrl : " + currentUrl);
                if (reqUrl.equals(currentUrl)) {
                    loadFailtUrl();
                }
            }
    
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                Log.e(TAG, "error : " + error);
                // 接受所有网站的证书
                handler.proceed();
                // 默认是handler.cancel();
    //            super.onReceivedSslError(view, handler, error);
            }
        }
    
        static class CusWebChromeClient extends WebChromeClient 
        {
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return super.onJsAlert(view, url, message, result);
            }
    
            @Override
            public void onReceivedTitle(WebView view, String title) {
                // 404 , 502 Bad Gateway...
                Log.e(TAG, "onReceivedTitle : " + title);
                super.onReceivedTitle(view, title);
            }
        }
    
    /*****************
         * Android与JS交互接口
         **************************/
    
        private final class Contact {
            // JavaScript调用此方法
    
            /**
             * 关闭当前的原生界面
             */
            @JavascriptInterface
            public void goBack() {
                // 调用JS中的方法
                finish();
            }
    }
    

    二、Android调用Js:
    1.通过loadUrl()

    // 此方法能调用js函数,但无法直接获取js函数的返回值。需要js再调用一个android方法把返回值传
    // 过来才行
    webView.loadUrl("javascript:attentionBtnClick('" + finalButtonTxt + "', '" + 
    finalButtomId + "')");
    

    2.通过evaluateJavascript()

    // 此方法需要 api>= 19才能用。此法能直接获取js的返回值
    webView.evaluateJavascript("getContent()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.e(TAG, "--- evaluateJavascript --- js 返回值 : " + value);
                    showMsg(value, Toast.LENGTH_SHORT);
                }
            });
    

    三、Js调用Android:

    window.contact.goBack();
    

    四、WebView加载https

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }
    
    webView.setWebViewClient(new WebViewClient(){
                @Override
                public void onReceivedSslError(WebView view, SslErrorHandler handler, 
                SslError error) {
                    // 接受所有网站的证书
                handler.proceed();
                // 默认是handler.cancel();
    //            super.onReceivedSslError(view, handler, error);
                }
            });
    

    五、WebView加载http及https混合页面(例如,https页面有一个http的图片):

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Log.v(TAG, "版本大于21,启动setMixedContentMode(0)");
                 // 解决http及https混合情况下页面加载问题
     setting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            } else {
                Log.v(TAG, "版本小于21,无须启动setMixedContentMode(0)");
            }
    

    相关文章

      网友评论

          本文标题:WebView加载http、https细节,交互及注意事项

          本文链接:https://www.haomeiwen.com/subject/nsajeftx.html