1

What my app does: Load index.html to WebView

index.html's Code:

<html>
<body>
<a href="Posts10.html"><h2>Interesting Stuff</h2></a>
</body>
</html>

So whenever I click on the link, It gives me this error:

enter image description here

index.html and Posts10.html are located in

Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"/CachedPosts"

a.k.a

"/data/user/0/com.companyname.theoctant/files/CachedPosts"
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
SunAwtCanvas
  • 1,261
  • 1
  • 13
  • 38
  • Is this within Forms' project or via a `Xamarin.Android` project? And what are you setting the WebView's BaseURL to be? – SushiHangover Jun 30 '18 at 03:13
  • @SushiHangover When there is an internet connection, the WebView opens a url. But if there isn't, it opens a html file. And Xamarin Forms – SunAwtCanvas Jun 30 '18 at 03:19

2 Answers2

2

This may help. From the Xamarin docs:

On Android, place HTML, CSS, and images in the Assets folder with build action AndroidAsset as demonstrated below:

https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/webview?tabs=vswin#android

afilbert
  • 1,430
  • 2
  • 24
  • 25
  • Can I save it programmatically in the `Assets` folder? – SunAwtCanvas Jun 30 '18 at 03:11
  • As @SushiHangover mentioned, I believe the Assets are compile time assets, which means you won't be able to change them during runtime. There might be a workaround, however, mentioned here: https://stackoverflow.com/a/3845559/119041 – afilbert Jun 30 '18 at 03:16
  • @SushiHangover @afilbert Then this doesn't solve my issue :/ because my program also downloads the Posts10.html programmatically :/ Is there any way for my html file to open the html file stored in `Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"/CachedPosts"` ?? – SunAwtCanvas Jun 30 '18 at 03:16
0

When there is an internet connection, the WebView opens a url. But if there isn't, it opens a html file. And Xamarin Forms

All you need to do is swap the type of WebViewSource that you are using and assign the proper properties to it wether you are connected or not.

So for a Forms' WebView, if you are "Internet" connected, create a UrlWebViewSource and assign the property Url, but if not, create a HtmlWebViewSource and assign the BaseUrl to either NSBundle.MainBundle.BundlePath or file:///android_asset/ for static app bundled resources, or your custom cache directory.

Something like this:

WebViewSource webViewSource;
if (InternetConnected)
{
    webViewSource = new UrlWebViewSource { Url = "https://stackoverflow.com" };
}
else
{
    string baseUrl = cacheDir;
    webViewSource = new HtmlWebViewSource { BaseUrl = baseUrl, Html = cachedHtml };
}
webView.Source = webViewSource;
SushiHangover
  • 73,120
  • 10
  • 106
  • 165