简体   繁体   中英

Xamarin Forms WebView loading mixed content in Android

I have a Xamarin Forms WebView. The Source is a Webpage which contains mixed content (links to https and http resources). It loads in Xamarin Forms iOS without problems, however in Android it will not load, and I suspect that the problems is the mixed content.

How can I set MixedContentMode?

There is documentation at https://docs.microsoft.com/de-de/dotnet/api/xamarin.forms.platformconfiguration.androidspecific.webview.setmixedcontentmode?view=xamarin-forms

But I don't understand how to use that. Can someone give me an example?

Thanks a lot.

It depends a little bit if you have defined your WebView in code or XAML.

If you defined it in code, make sure you have a reference to it by the variable name, for instance:

var myWebView = new WebView();

myWebView is what I am talking about in this case.

Then, include this using at the top of your class:

using Xamarin.Forms.PlatformConfiguration.AndroidSpecific;

Then add this line after you have initialized the WebView :

myWebView.On<Android>().SetMixedContentMode(MixedContentHandling.AlwaysAllow);

From XAML, add the right namespace to the root of your page, like this:

<ContentPage xmlns:android="clr-namespace:Xamarin.Forms.PlatformConfiguration.AndroidSpecific;assembly=Xamarin.Forms.Core" ....>

Then, on your WebView , you can just add another attribute: <WebView ... android:WebView.MixedContentMode="AlwaysAllow" />

These are the so-called platform-specifics. You can set platform-specific properties directly from Xamarin.Forms shared code as opposed to having a custom renderer in place for one simple property.

Read more on it here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/platform/platform-specifics/ and consuming (this specific case, actually) here: https://docs.microsoft.com/en-us/xamarin/xamarin-forms/platform/platform-specifics/consuming/android#enabling-mixed-content-in-a-webview

A note on the actual thing you are setting here, in the example I simply set it to AlwaysAllow , ensure you know what each option does and set it to the most secure one. Here is a small explanation, taken from the Microsoft Docs:

  • AlwaysAllow – indicates that the WebView will allow an HTTPS origin to load content from an HTTP origin.
  • NeverAllow – indicates that the WebView will not allow an HTTPS origin to load content from an HTTP origin.
  • CompatibilityMode – indicates that the WebView will attempt to be compatible with the approach of the latest device web browser. Some HTTP content may be allowed to be loaded by an HTTPS origin and other types of content will be blocked. The types of content that are blocked or allowed may change with each operating system release.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM