Android webview, loading javascript file in assets folder

前端 未结 5 1888
我在风中等你
我在风中等你 2020-11-29 01:09

I\'ve seen this question has been asked a lot of times, but still can\'t manage to get my code working.

I want my webview to load some URL (say www.google.c

5条回答
  •  失恋的感觉
    2020-11-29 01:56

    With the following two conditions given:

    • minSdkVersion 21
    • targetSdkVersion 28

    I am able to successfully load any local asset (js, png, css) via the following Java code

    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
        Uri uri = request.getUrl();
        if (uri.getHost().equals("assets")) {
            try {
                return new WebResourceResponse(
                    URLConnection.guessContentTypeFromName(uri.getPath()),
                    "utf-8",
                    MainActivity.this.getAssets().open(uri.toString().substring(15)));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    

    And in the HTML code I can use

    
    
     
    
    

    In Java the following then also works (you'd also need to add a favicon.ico to the assets)

    webView.loadUrl("https://assets/example.html");
    

    Using https:// as the scheme allows me to load local assets from a page served via HTTPS without security issues due to mixed-content.

    None of these require to be set:

    webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
    webSettings.setDomStorageEnabled(true);
    webSettings.setAllowContentAccess(true);
    webSettings.setAllowFileAccess(true);
    webSettings.setAllowFileAccessFromFileURLs(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);    
    

提交回复
热议问题