Jaa


WebView JavaScript Alerts on Windows

This platform-specific enables a WebView to display JavaScript alerts in a UWP message dialog. It's consumed in XAML by setting the WebView.IsJavaScriptAlertEnabled attached property to a boolean value:

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

Alternatively, it can be consumed from C# using the fluent API:

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

The WebView.On<Windows> method specifies that this platform-specific will only run on the Universal Windows Platform. The WebView.SetIsJavaScriptAlertEnabled method, in the Xamarin.Forms.PlatformConfiguration.WindowsSpecific namespace, is used to control whether JavaScript alerts are enabled. In addition, the WebView.SetIsJavaScriptAlertEnabled method can be used to toggle JavaScript alerts by calling the IsJavaScriptAlertEnabled method to return whether they are enabled:

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

The result is that JavaScript alerts can be displayed in a UWP message dialog:

WebView JavaScript alert platform-specific