Webview BaseURL in Xamarin.Forms on UWP and Window

2019-06-21 20:35发布

问题:

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.

回答1:

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



回答2:

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