Android webview本地文件设置root

Android webview local file setting root

我正在 Android 中使用 webview 加载本地 Web 应用程序:

view.loadUrl("https://appassets.androidplatform.net/assets/dist/index.html")

然而,当我在 JavaScript 中检查当前路线时,它显示 https://appassets.androidplatform.net/assets/dist/index.html

这让路由和文件加载之类的事情变得很痛苦 - 有没有办法设置加载应用程序的根目录,这样我就可以避免整个 /assets/

查看 WebViewAssetLoader 那里的代码片段正是您所需要的。所以你基本上只需要将所有可以由 assetsLoader 处理的请求转发给它,并使用它 returns.

的响应
final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
          .addPathHandler("/assets/", new AssetsPathHandler(this))
          .build();

 webView.setWebViewClient(new WebViewClient() {
     @Override
     @RequiresApi(21)
     public WebResourceResponse shouldInterceptRequest(WebView view,
                                      WebResourceRequest request) {
         return assetLoader.shouldInterceptRequest(request.getUrl());
     }

     @Override
     @SuppressWarnings("deprecation") // for API < 21
     public WebResourceResponse shouldInterceptRequest(WebView view,
                                      WebResourceRequest request) {
         return assetLoader.shouldInterceptRequest(Uri.parse(request));
     }
 });

 WebSettings webViewSettings = webView.getSettings();
 // Setting this off for security. Off by default for SDK versions >= 16.
 webViewSettings.setAllowFileAccessFromFileURLs(false);
 // Off by default, deprecated for SDK versions >= 30.
 webViewSettings.setAllowUniversalAccessFromFileURLs(false);
 // Keeping these off is less critical but still a good idea, especially if your app is not
 // using file:// or content:// URLs.
 webViewSettings.setAllowFileAccess(false);
 webViewSettings.setAllowContentAccess(false);

 // Assets are hosted under http(s)://appassets.androidplatform.net/assets/... .
 // If the application's assets are in the "main/assets" folder this will read the file
 // from "main/assets/www/index.html" and load it as if it were hosted on:
 // https://appassets.androidplatform.net/assets/www/index.html
 webview.loadUrl("https://appassets.androidplatform.net/assets/www/index.html");