【问题标题】:Android webview local file setting rootAndroid webview本地文件设置root
【发布时间】:2022-01-17 19:35:58
【问题描述】:

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

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

但是,当我在 JavaScript 中检查当前路由时,它会显示 https://appassets.androidplatform.net/assets/dist/index.html

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

【问题讨论】:

    标签: javascript android webview android-webview


    【解决方案1】:

    看看WebViewAssetLoader 那里的代码 sn-p 正是您所需要的。所以你基本上只需要将 assetsLoader 可以处理的所有请求转发给它,并使用它返回的响应。

    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");
    

    【讨论】:

    • 你能给我一个代码示例吗?我觉得我也试过了,但没有成功?
    • 基本上代码就是我链接的那个页面就够了,你不需要再做任何改动,我已经在解决方案中添加了示例代码,试试看跨度>
    • 运行 window.location.href 时它会说appassets.androidplatform.net/assets/www/index.html 我的问题是是否可以在目录的根目录下托管它
    • 我并没有真正了解您的目标,您的网站结构如何?它是否完全本地化并嵌入到应用的资产中?
    • 是的,这是正确的
    猜你喜欢
    • 2013-12-23
    • 2012-12-22
    • 2020-01-16
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 2014-01-19
    • 2014-02-28
    相关资源
    最近更新 更多