Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webview BaseURL in Xamarin.Forms on UWP and Windows Phone 8.1

In my shared portable Xamarin project, this works on UWP, Windows Phone 8.1 and Windows 8.1:

HtmlWebViewSource htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<html><body><img src='ms-appx-web:///Assets/somePicture.png' /></body></html>";
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
WebView webView = new WebView
{
        Source = htmlSource,
};

Obviously, this isn't cross-platform (iOS and Android). I want this, but it doesn't work on UWP, Windows Phone 8.1 and Windows 8.1:

HtmlWebViewSource htmlSource = new HtmlWebViewSource();
htmlSource.Html = @"<html><body><img src='somePicture.png' /></body></html>";
htmlSource.BaseUrl = DependencyService.Get<IBaseUrl>().Get();
WebView webView = new WebView
{
        Source = htmlSource,
};

IBaseUrl:

public interface IBaseUrl { string Get(); }

BaseUrl implementation for UWP, Windows Phone 8.1 and Windows 8.1, taken from a Windows Phone 8.0 sample project:

[assembly: Dependency(typeof(MyApp.UWP.BaseUrl))]
namespace MyApp.UWP
{
    public class BaseUrl : IBaseUrl
    {
        public string Get()
        {
            return ""; // "ms-appx-web:///Assets/" doesn't work
        }
    }
}

I've tried different variations of returning BaseUrl of "ms-appx-web:///Assets/", "ms-appx-web:///", placing the files in the project root or in the “Assets” dir, nothing works.

As far as I can tell, this used to work on Windows Phone 8.0.

like image 619
Zdeněk Gromnica Avatar asked Apr 25 '16 14:04

Zdeněk Gromnica


2 Answers

What about Device.OnPlatform?

var urlIos = @"somePicture.png";
var urlAndroid = @"somePicture.png";
var urlUWP = @"ms-appx-web:///Assets/somePicture.png";
htmlSource.Html = string.Format(@"<html><body><img src='{0}' /></body></html>", Device.OnPlatform(urlIos, urlAndroid, urlUWP));
like image 58
Matt Avatar answered Oct 24 '22 00:10

Matt


As of Xamarin Forms 2.3.1, WebViewRenderer for Windows RT simply ignores the BaseUrl (https://github.com/xamarin/Xamarin.Forms/blob/2.3.1/Xamarin.Forms.Platform.WinRT/WebViewRenderer.cs#L26). However, there is a fix for this on the 2.3.2 branch: https://github.com/xamarin/Xamarin.Forms/blob/2.3.2/Xamarin.Forms.Platform.WinRT/WebViewRenderer.cs

like image 1
Michał Dudak Avatar answered Oct 24 '22 00:10

Michał Dudak