WebView 使用根路径加载 HTML 内容

WebView load HTML content with root path

我正在尝试在 Xamarin 的 Android WebView 中加载本地保存的 HTML 文件。我制作了一个 CustomRenderer 来访问 Android WebView 的本机功能。 HTML 内容加载得很好,但问题是我的 css 和 js 引用未加载。我尝试使用 LoadDataWithBaseURL() 函数操作 baseUrl,但无论出于何种原因样式表和脚本未加载。

我的引用总是一样的,link 看起来像这样 href="/css/stylesheet.css"。我可以操纵 HTML 中的字符串,但我想尝试通过使用不同的 Base URL.

加载内容来实现这一点

我的文件存储如下:

/data/user/0/<api-key>/files/wwwroot/css/stylesheet.css"

并且脚本位于不同的子文件夹中,等等。 我在 WebView 中设置了以下设置:

string baseUrl = _hhwebView.WWWROOT_PATH; ///data/user/0/<api-key>/files/wwwroot/
_webView.Settings.AllowContentAccess = true;
_webView.Settings.AllowFileAccess = true;
_webView.Settings.AllowFileAccessFromFileURLs = true;
_webView.Settings.AllowUniversalAccessFromFileURLs = true;
_webView.LoadDataWithBaseURL(baseUrl, content, "text/html", "UTF-8", null);

有人知道我该如何实现吗?提前致谢。

我通过覆盖 WebViewClient 上的 ShouldInterceptRequest 方法解决了这个问题,而不是从字符串中加载内容,而是通过 URL 像这样加载它:

_webView.LoadUrl("file://" + _hhwebView.WWWROOT_PATH + "/content.html");

我的覆盖方法如下所示:

public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest request)
{
    string url = request.Url.ToString();
    if (url.Contains(".css"))
    {
        string file = url.Replace("file:///", "");
        return ReturnResourceFile("text/css", "css", file.Split('/')[1]);
    }
    if (url.Contains(".js"))
    {
        string file = url.Replace("file:///", "");
        return ReturnResourceFile("text/javascript", "js", file.Split('/')[1]);
    }
    return base.ShouldInterceptRequest(view, request);
}


private WebResourceResponse ReturnResourceFile(string mimeType, string extension, string file)
{
    return new WebResourceResponse(mimeType, "UTF-8", File.OpenRead(Path.Combine(_hhwebView.WWWROOT_PATH, extension, file)));
}