Windows 上的 WebView JavaScript 警报

这项平台特定的功能可启用了 WebView,以便在 UWP 消息对话框中显示 JavaScript 警告。 通过将 WebView.IsJavaScriptAlertEnabled 附加属性设置为 boolean 值在 XAML 中使用它:

<ContentPage ...
             xmlns:windows="clr-namespace:Xamarin.Forms.PlatformConfiguration.WindowsSpecific;assembly=Xamarin.Forms.Core">
    <StackLayout>
        <WebView ... windows:WebView.IsJavaScriptAlertEnabled="true" />
        ...
    </StackLayout>
</ContentPage>

或者,可以使用 Fluent API 从 C# 使用它:

using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.PlatformConfiguration.WindowsSpecific;
...

var webView = new Xamarin.Forms.WebView
{
  Source = new HtmlWebViewSource
  {
    Html = @"<html><body><button onclick=""window.alert('Hello World from JavaScript');"">Click Me</button></body></html>"
  }
};
webView.On<Windows>().SetIsJavaScriptAlertEnabled(true);

WebView.On<Windows> 方法指定此特定于平台的功能仅在通用 Windows 平台上运行。 Xamarin.Forms.PlatformConfiguration.WindowsSpecific 命名空间中的 WebView.SetIsJavaScriptAlertEnabled 方法用于控制是否启用 JavaScript 警报。 此外,WebView.SetIsJavaScriptAlertEnabled 方法还可用于切换 JavaScript 警报,方法是调用 IsJavaScriptAlertEnabled 方法返回它们是否启用的结果:

_webView.On<Windows>().SetIsJavaScriptAlertEnabled(!_webView.On<Windows>().IsJavaScriptAlertEnabled());

结果是 JavaScript 警报可以在 UWP 消息对话框中显示:

特定于 WebView JavaScript 警报平台