I'm trying to load a local saved HTML file in my Android WebView in Xamarin. I made a CustomRenderer to access the native functionality of the Android WebView. The HTML content is loaded just fine, but the problem is that my css and js references are not loaded in. I tried to manipulate the baseUrl with the LoadDataWithBaseURL()
function, but for whatever reason the stylesheets and scripts are not loaded.
My referencing is always the same, a link looks like this href="/css/stylesheet.css"
. I could manipulate the strings in the HTML but i want to try to achieve this with loading the content with a different Base URL.
My files are stored like the following:
/data/user/0/<api-key>/files/wwwroot/css/stylesheet.css"
And the scripts are in a different subfolder, etc. I'm having the following settings set in my 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);
Anyone has an idea how i can achieve this? Thanks in advance.
I solved the problem by overriding ShouldInterceptRequest
method on WebViewClient
and instead of loading the content from a string i loaded it via URL like this:
_webView.LoadUrl("file://" + _hhwebView.WWWROOT_PATH + "/content.html");
My override method looks like that:
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)));
}