androidandroid-webviewwebviewclient

WebViewClient::onReceivedSslError is not called


I have attached my WebViewClient implementation to my WebView.

appView.setWebViewClient(new AppViewClient());

My onReceivedSslError and onReceivedError implementations are called with all expected errors except for Mixed Content error.

My implementation for both methods:

Log.i(TAG, "Error Cought");

As I said, they are called on various errors except the Mixed Content error. My request is blocked without calling either of these methods.


Solution

  • Which API version are you using? MIX CONTENT was allowed, by default, before 21.

    You can try adding this setting in web view:

    webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
    

    For API level below 21 :

    try {
        Method m = WebSettings.class.getMethod("setMixedContentMode", int.class);
        if ( m != null ) {
    
         m.invoke(webView.getSettings(), 1); //MIXED_CONTENT_NEVER_ALLOW
    
        }
    }
    catch (Exception ex) {
    
    }
    

    Good to know that you already know about MixedContentMode :) I can suggest 2 things to try.

    1. Use console message to identify this error. You can do a string match to check the MIX CONTENT error.
    myWebView.setWebChromeClient(new WebChromeClient() {
      public void onConsoleMessage(String message, int lineNumber, String sourceID) {
        Log.d("MyApplication", message + " -- From line "
                             + lineNumber + " of "
                             + sourceID);
      }
    });
    
    1. Intercept request and check the url. Check the WebActivity implementation in source code.

      mWebView.setWebViewClient(new WebViewClient() {
                  @Override
                  public WebResourceResponse shouldInterceptRequest(WebView view,
                          WebResourceRequest request) {
                      String url = request.getUrl().toString();
                      if (!URLUtil.isHttpsUrl(url)) {
                          Logger.loge("Secure connection required, but insecure URL requested "
                                  + "explicitly, or as a part of the page.");
                          return createNewSecurityErrorResponse();
                      }
                      return super.shouldInterceptRequest(view, request);
                  }
              });
      
      
      
      
      private WebResourceResponse createNewSecurityErrorResponse() {
              WebResourceResponse response = new WebResourceResponse("text/plain", "UTF-8", null);
              response.setStatusCodeAndReasonPhrase(HTTP_FORBIDDEN, "Secure connection required");
              return response;
          }