WebView WebView WebView Class

Provides a control that hosts HTML content in an app.

Syntax

Declaration

public sealed class WebViewpublic sealed class WebViewPublic NotInheritable Class WebView
<WebView .../>
        

Remarks

Use the WebView control to host web content in your app.

WebView is not a Control subclass and thus does not have a control template. You can set various properties to control some visual aspects of the WebView. The display area is constrained by the Width and Height properties. To translate, scale, skew, and rotate a WebView, use the RenderTransform property. To control the opacity of the WebView, set the Opacity property. To specify a color to use as the web page background when the HTML content does not specify a color, set the DefaultBackgroundColor property.

You can get the title of the HTML document currently displayed in the WebView by using the DocumentTitle property.

Although WebView is not a Control subclass, it will receive keyboard input focus and participate in the tab sequence. It provides a Focus(Windows.UI.Xaml.FocusState) method, and GotFocus and LostFocus events, but it has no tab-related properties. Its position in the tab sequence is the same as its position in the XAML document order. The tab sequence includes all elements in the WebView content that can receive input focus.

As indicated in the Events table, WebView doesn’t support most of the user input events inherited from UIElement, such as KeyDown, KeyUp, and PointerPressed. A common workaround is to use InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String}) with the JavaScript eval function to use the HTML event handlers, and to use window.external.notify from the HTML event handler to notify the application using ScriptNotify.

In apps compiled for Windows 10, WebView uses the Microsoft Edge rendering engine to display HTML content. In apps compiled for Windows 8 or Windows 8.1, WebView uses Internet Explorer 11 in document mode. It does not support any Microsoft ActiveX controls or plugins like Microsoft Silverlight or Portable Document Format (PDF) files.

WebView provides several API for basic navigation: GoBack(), GoForward(), Stop(), Refresh(), CanGoBack, and CanGoForward. You can use these to add typical web browsing capabilities to your app.

To set the initial content of the WebView, set the Source property in XAML. The XAML parser automatically converts the string to a Uri.


<!-- Source file is on the web. -->
<WebView x:Name="webView1" Source="http://www.contoso.com"/>

<!-- Source file is in local storage. -->
<WebView x:Name="webView2" Source="ms-appdata:///local/intro/welcome.html"/>

<!-- Source file is in the app package. -->
<WebView x:Name="webView3" Source="ms-appx-web:///help/about.html"/>

The Source property can be set in code, but rather than doing so, you typically use one of the Navigate methods to load content in code.

To load web content, use the Navigate(Windows.Foundation.Uri) method with a Uri that uses the http or https scheme.

webView1.Navigate("http://www.contoso.com");

To navigate to a Uniform Resource Identifier (URI) with a POST request and HTTP headers, use the NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage) method. This method supports only Post and Get for the Method property value.

To load uncompressed and unencrypted content from your app’s LocalFolder or TemporaryFolder data stores, use the Navigate(Windows.Foundation.Uri) method with a Uri that uses the ms-appdata scheme. The WebView support for this scheme requires you to place your content in a subfolder under the local or temporary folder. This enables navigation to Uniform Resource Identifier (URI) such as ms-appdata:///local/folder/file.html and ms-appdata:///temp/folder/file.html. (To load compressed or encrypted files, see @Windows.UI.Xaml.Controls.WebView.NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver).)

Each of these first-level subfolders is isolated from the content in other first-level subfolders. For example, you can navigate to ms-appdata:///temp/folder1/file.html, but you can’t have a link in this file to ms-appdata:///temp/folder2/file.html. However, you can still link to HTML content in the app package using the ms-appx-web scheme, and to web content using the http and https Uniform Resource Identifier (URI) schemes.

webView1.Navigate("ms-appdata:///local/intro/welcome.html");

To load content from the your app package, use the Navigate(Windows.Foundation.Uri) method with a Uri that uses the ms-appx-web scheme.

webView1.Navigate("ms-appx-web:///help/about.html");

You can load local content through a custom resolver using the NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver) method. This enables advanced scenarios such as downloading and caching web-based content for offline use, or extracting content from a compressed file.

Responding to navigation events

WebView provides several events that you can use to respond to navigation and content loading states. The events occur in the following order for the root WebView content:

  • NavigationStarting - Occurs before the WebView navigates to new content. You can cancel navigation in a handler for this event by setting the Cancel property to true.```csharp webView1.NavigationStarting += webView1_NavigationStarting;

private void webView1_NavigationStarting(object sender, WebViewNavigationStartingEventArgs args) { // Cancel navigation if URL is not allowed. (Implemetation of IsAllowedUri not shown.) if (!IsAllowedUri(args.Uri)) args.Cancel = true; }



+ @Windows.UI.Xaml.Controls.WebView.ContentLoading - Occurs when the @Windows.UI.Xaml.Controls.WebView has started loading new content.```csharp
webView1.ContentLoading += webView1_ContentLoading;

private void webView1_ContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
{
    // Show status.
    if (args.Uri != null)
    {
        statusTextBlock.Text = "Loading content for " + args.Uri.ToString();
    }
}
  • DOMContentLoaded - Occurs when the WebView has finished parsing the current HTML content.```csharp webView1.DOMContentLoaded += webView1_DOMContentLoaded;

private void webView1_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args) { // Show status. if (args.Uri != null) { statusTextBlock.Text = "Content for " + args.Uri.ToString() + " has finished loading"; } }



+ @Windows.UI.Xaml.Controls.WebView.NavigationCompleted - Occurs when the @Windows.UI.Xaml.Controls.WebView has finished loading the current content or if navigation has failed. To determine whether navigation has failed, check the @Windows.UI.Xaml.Controls.WebViewNavigationCompletedEventArgs.IsSuccess and @Windows.UI.Xaml.Controls.WebViewNavigationCompletedEventArgs.WebErrorStatus properties of the @Windows.UI.Xaml.Controls.WebViewNavigationCompletedEventArgs class.```csharp
webView1.NavigationCompleted += webView1_NavigationCompleted;

private void webView1_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{
    if (args.IsSuccess == true)
    {
        statusTextBlock.Text = "Navigation to " + args.Uri.ToString() + " completed successfully.";
    }
    else
    {
        statusTextBlock.Text = "Navigation to: " + args.Uri.ToString() + 
                               " failed with error " + args.WebErrorStatus.ToString();
    }
}

Similar events occur in the same order for each iframe in the WebView content:

Responding to potential problems

You can respond to potential problems with the content such as long running scripts, content that WebView can't load, and warnings of unsafe content.

Your app might appear unresponsive while scripts are running. The LongRunningScriptDetected event occurs periodically while the WebView executes JavaScript and provides an opportunity to interrupt the script. To determine how long the script has been running, check the ExecutionTime property of the WebViewLongRunningScriptDetectedEventArgs. To halt the script, set the event args StopPageScriptExecution property to true. The halted script will not execute again unless it is reloaded during a subsequent WebView navigation.

The WebView control cannot host arbitrary file types. When an attempt is made to load content that the WebView can't host, the UnviewableContentIdentified event occurs. You can handle this event and notify the user, or use the Launcher class to redirect the file to an external browser or another app.

Similarly, the UnsupportedUriSchemeIdentified event occurs when a Uniform Resource Identifier (URI) scheme that's not supported is invoked in the web content, such as fbconnect:// or mailto://. You can handle this event to provide custom behavior instead of allowing the default system launcher to launch the Uniform Resource Identifier (URI).

The UnsafeContentWarningDisplaying event occurs when the WebView shows a warning page for content that was reported as unsafe by the SmartScreen Filter. If the user chooses to continue the navigation, subsequent navigation to the page will not display the warning nor fire the event.

Handling special cases for WebView content

You can use the ContainsFullScreenElement property and ContainsFullScreenElementChanged event to detect, respond to, and enable full-screen experiences in web content, such as full-screen video playback. For example, you may use the ContainsFullScreenElementChanged event to resize the WebView to occupy the entirety of your app view, or, as the following example illustrates, put a windowed app in full screen mode when a full screen web experience is desired.


// Assume webView is defined in XAML
webView.ContainsFullScreenElementChanged += webView_ContainsFullScreenElementChanged;

private void webView_ContainsFullScreenElementChanged(WebView sender, object args)
{
    var applicationView = ApplicationView.GetForCurrentView();

    if (sender.ContainsFullScreenElement)
    {
        applicationView.TryEnterFullScreenMode();
    }
    else if (applicationView.IsFullScreenMode)
    {
        applicationView.ExitFullScreenMode();
    }
}

You can use the NewWindowRequested event to handle cases where hosted web content requests a new window to be displayed, such as a popup window. You can use another WebView control to display the contents of the requested window.

Use PermissionRequested event to enable web features that require special capabilities. These currently include geolocation, IndexedDB storage, and user audio and video (for example, from a microphone or webcam). If your app accesses user location or user media, you still are required to declare this capability in the app manifest. For example, an app that uses geolocation needs the following capability declarations at minimum in Package.appxmanifest:

  <Capabilities>
    <Capability Name="internetClient"/>
    <DeviceCapability Name="location"/>
  </Capabilities>

In addition to the app handling the PermissionRequested event, the user will have to approve standard system dialogs for apps requesting location or media capabilities in order for these features to be enabled.

Here is an example of how an app would enable geolocation in a map from Bing:


// Assume webView is defined in XAML
webView.PermissionRequested += webView_PermissionRequested;

private void webView_PermissionRequested(WebView sender, WebViewPermissionRequestedEventArgs args)
{
    if (args.PermissionRequest.PermissionType == WebViewPermissionType.Geolocation &&
        args.PermissionRequest.Uri.Host == "www.bing.com")
    {
        args.PermissionRequest.Allow();
    }
}

If your app requires user input or other asynchronous operations to respond to a permission request, use the Defer() method of WebViewPermissionRequest to create a WebViewDeferredPermissionRequest that can be acted upon at a later time. See Defer().

If users must securely log out of a website hosted in WebView, or in other cases when security is important, call the static method ClearTemporaryWebDataAsync() to clear out all locally cached content from a WebView session. This prevents malicious users from accessing sensitive data.

Interacting with WebView content

You can interact with the content of the WebView by using the InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String}) method to invoke or inject script into the WebView content, and the ScriptNotify event to get information back from the WebView content.

To invoke JavaScript inside the WebView content, use the InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String}) method. The invoked script can return only string values.

For example, if the content of a WebView named webView1 contains a function named setDate that takes 3 parameters, you can invoke it like this.


string[] args = {"January", "1", "2000"};
string returnValue = await webView1.InvokeScriptAsync("setDate", args);

You can use InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String}) with the JavaScript eval function to inject content into the web page.

Here, the text of a XAML TextBox (nameTextBox.Text) is written to a div in an HTML page hosted in webView1.


private async void Button_Click(object sender, RoutedEventArgs e)
{
    string functionString = String.Format("document.getElementById('nameDiv').innerText = 'Hello, {0}';", nameTextBox.Text);
    await webView1.InvokeScriptAsync("eval", new string[] { functionString });
}

Scripts in the WebView content can use window.external.notify with a string parameter to send information back to your app. To receive these messages, handle the ScriptNotify event.

To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's Uniform Resource Identifier (URI) in the ApplicationContentUriRules section of the app manifest. (You can do this in Microsoft Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS, and may contain subdomain wildcards (for example, https://.microsoft.com) but they cannot contain domain wildcards (for example, https://.com and https://.). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString(System.String).

Accessing the Windows Runtime in WebView

Starting in Windows 10, you can use the AddWebAllowedObject(System.String,System.Object) method to inject an instance of a native class from a Windows Runtime component into the JavaScript context of the WebView. This allows full access to the native methods, properties, and events of that object in the JavaScript content of that WebView. The class must be decorated with the AllowForWebAttribute attribute.

For example, this code injects an instance of MyClass imported from a Windows Runtime component into WebView.


private void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) 
{ 
    if (args.Uri.Host == "www.contoso.com")  
    { 
        webView.AddWebAllowedObject("nativeObject", new MyClass()); 
    } 
}

For more info, see AddWebAllowedObject(System.String,System.Object).

In addition, trusted JavaScript content in WebView can be allowed to directly access Windows RuntimeAPI. This provides powerful native capabilities for web apps hosted in WebView. To enable this feature, the Uniform Resource Identifier (URI) for trusted content must be whitelisted in the ApplicationContentUriRules of the app in Package.appxmanifest, with WindowsRuntimeAccess specifically set to "all".

This example shows a section of the app manifest. Here, a local Uniform Resource Identifier (URI) is given access to the Windows Runtime.

  <Applications>
    <Application Id="App"
      ...

      <uap:ApplicationContentUriRules>
        <uap:Rule Match="ms-appx-web:///Web/App.html" WindowsRuntimeAccess="all" Type="include"/>
      </uap:ApplicationContentUriRules>
    </Application>
  </Applications>

Options for web content hosting

Starting in Windows 10, you can use the Settings property (of type WebViewSettings ) to control whether JavaScript and IndexedDB are enabled. For example, if you use WebView to display strictly static content, you might want to disable JavaScript for best performance.

Capturing WebView content

To enable sharing WebView content with other apps, use the CaptureSelectedContentToDataPackageAsync() method, which returns the selected content as a DataPackage. This method is asynchronous, so you must use a deferral to prevent your DataRequested event handler from returning before the asynchronous call is complete.

To get a preview image of the WebView 's current content, use the CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream) method. This method creates an image of the current content and writes it to the specified stream.

Threading behavior

By default, WebView content is hosted on the UI thread on devices in the desktop device family, and off the UI thread on all other devices. You can use the DefaultExecutionMode static property to query the default threading behavior for the current client. If necessary, you can use the @Windows.UI.Xaml.Controls.WebView.#ctor(Windows.UI.Xaml.Controls.WebViewExecutionMode) constructor to override this behavior.

Note

There might be performance issues when hosting content on the UI thread on mobile devices, so be sure to test on all target devices when you change DefaultExecutionMode.

A WebView that hosts content off the UI thread is not compatible with parent controls that require gestures to propagate up from the WebView control to the parent, such as FlipView, ScrollViewer, and other related controls. These controls will not be able to receive gestures initiated in the off-thread WebView. In addition, printing off-thread web content is not directly supported – you should print an element with WebViewBrush fill instead.

Notes for previous versions

Windows 8.1

The following WebView APIs are deprecated in Windows 8.1:

On Windows only, you can handle the UnsafeContentWarningDisplaying event. This event occurs when the WebView shows a warning page for content that was reported as unsafe by the SmartScreen Filter. If the user chooses to continue the navigation, subsequent navigation to the page will not display the warning nor fire the event. This event is not implemented for Windows Phone.

When you invoke JavaScript inside the WebView by calling the InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String}) method, functions that require a secondary window, like Alert, are not supported.

Windows Phone 8.

1

The UnsafeContentWarningDisplaying event is not implemented for Windows Phone prior to Windows 10.

Windows 8

These remarks apply only to apps compiled for Windows 8, even when running on Windows 8.1 or later.

In Windows 8,WebView has the characteristic that other UI regions such as controls cannot be rendered on top of the WebView. This "airspace problem" is because of how window regions are handled internally, particularly how input events are processed and how the screen draws. If you want to render HTML content and also place other UI elements on top of that HTML content, you should use WebViewBrush as the render area. The WebView still provides the HTML source information, and you reference that WebView through the SourceName property. WebViewBrush does not have this overlay limitation.

If you want to display an interactive WebView that only occasionally has overlapping content (such as a drop-down list or app bar), you can temporarily hide the WebView control when necessary, replacing it with an element using a WebViewBrush fill. Then, when the overlapping content is no longer present, you can display the original WebView again.

Note

The "airspace problem" has been fixed starting with Windows 8.1 and does not apply for apps targeting Windows 8.1 or Windows 10.

WebView always uses Internet Explorer 10 in document mode.

Examples

The following code example demonstrates how to navigate a WebView to a URI contained in a TextBox named Address.

try
{
    Uri targetUri = new Uri(Address.Text);
    webView1.Navigate(targetUri);
}
catch (FormatException ex)
{
    // Bad address.
}

The following code example demonstrates how to load local HTML into a WebView control.

webView2.NavigateToString(
    "<html><body><h2>This is an HTML fragment</h2></body></html>");

Constructors summary

Initializes a new instance of the WebView class.

Initializes a new instance of the WebView class with the specified execution mode.

Properties summary

Note

AllowedScriptNotifyUris is not supported in apps compiled for Windows 8.1. Instead, update the ApplicationContentUriRules section of the app manifest. For more info, see the Remarks section.

Gets or sets a safe list of URIs that are permitted to fire ScriptNotify events to this WebView.

Note

AllowedScriptNotifyUrisProperty is not supported in apps compiled for Windows 8.1. Instead, update the ApplicationContentUriRules section of the app manifest. For more info, see the Remarks section.

Identifies the AllowedScriptNotifyUris dependency property.

Note

AnyScriptNotifyUri is not supported in apps compiled for Windows 8.1. Instead, update the ApplicationContentUriRules section of the app manifest. For more info, see the Remarks section.

Gets a value that you can use to set the AllowedScriptNotifyUris property to indicate that any page can fire ScriptNotify events to this WebView.

Gets a value that indicates whether there is at least one page in the backward navigation history.

Identifies the CanGoBack dependency property.

Gets a value that indicates whether there is at least one page in the forward navigation history.

Identifies the CanGoForward dependency property.

Gets a value that indicates whether the WebView contains an element that supports full screen.

Identifies the ContainsFullScreenElement dependency property.

Note

DataTransferPackage may be altered or unavailable for releases after Windows 8.1. Instead, use CaptureSelectedContentToDataPackageAsync().

Gets a clipboard DataPackage as passed to the WebView.

Note

DataTransferPackageProperty may be altered or unavailable for releases after Windows 8.1. Instead, use CaptureSelectedContentToDataPackageAsync().

Identifies the DataTransferPackage dependency property.

Gets or sets the color to use as the WebView background when the HTML content does not specify a color.

Identifies the DefaultBackgroundColor dependency property.

Gets the default threading behavior of WebView instances in the current app.

Gets a collection of permission requests that are waiting to be granted or denied.

Gets the title of the page currently displayed in the WebView.

Identifies the DocumentTitle dependency property.

Gets a value that indicates whether the WebView hosts content on the UI thread or a non-UI thread.

Gets a WebViewSettings object that contains properties to enable or disable WebView features.

Gets or sets the Uniform Resource Identifier (URI) source of the HTML content to display in the WebView control.

Identifies the Source dependency property.

Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) down.

Identifies the XYFocusDown dependency property.

Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) left.

Identifies the XYFocusLeft dependency property.

Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) right.

Identifies the XYFocusRight dependency property.

Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) up.

Identifies the XYFocusUp dependency property.

Methods summary

Adds a native Windows Runtime object as a global parameter to the top level document inside of a WebView.

Creates a URI that you can pass to NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver).

Creates an image of the current WebView contents and writes it to the specified stream.

Asynchronously gets a DataPackage that contains the selected content within the WebView.

Clears the WebView 's cache and IndexedDB data.

Returns the deferred permission request with the specified Id.

Sets the input focus to the WebView.

Navigates the WebView to the previous page in the navigation history.

Navigates the WebView to the next page in the navigation history.

Executes the specified script function from the currently loaded HTML, with specific arguments.

Executes the specified script function from the currently loaded HTML, with specific arguments, as an asynchronous action.

Loads the HTML content at the specified Uniform Resource Identifier (URI).

Loads local web content at the specified URI using an IUriToStreamResolver.

Loads the specified HTML content as a new document.

Navigates the WebView to a URI with a POST request and HTTP headers.

Reloads the current content in the WebView.

Halts the current WebView navigation or download.

Events summary

Occurs when the status of whether the WebView currently contains a full screen element or not changes.

Occurs when the WebView has started loading new content.

Occurs when the WebView has finished parsing the current HTML content.

Occurs when a frame in the WebView has started loading new content.

Occurs when a frame in the WebView has finished parsing its current HTML content.

Occurs when a frame in the WebView has finished loading its content.

Occurs before a frame in the WebView navigates to new content.

Note

LoadCompleted may be altered or unavailable for releases after Windows 8.1. Instead, use NavigationCompleted.

Occurs when top-level navigation completes and the content loads into the WebView control or when an error occurs during loading.

Occurs periodically while the WebView executes JavaScript, letting you halt the script.

Occurs when the WebView has finished loading the current content or if navigation has failed.

Note

NavigationFailed may be altered or unavailable for releases after Windows 8.1. Instead, use NavigationCompleted.

Occurs when the WebView cannot complete the navigation attempt.

Occurs before the WebView navigates to new content.

Occurs when a user performs an action in a WebView that causes content to be opened in a new window.

Occurs when an action in a WebView requires that permission be granted.

Occurs when the content contained in the WebView control passes a string to the application by using JavaScript.

Occurs when the WebView shows a warning page for content that was reported as unsafe by SmartScreen Filter.

Occurs when an attempt is made to navigate to a Uniform Resource Identifier (URI) using a scheme that WebView doesn't support.

Occurs when the WebView attempts to download an unsupported file.

Constructors

  • WebView()
    WebView()
    WebView()
    WebView()

    Initializes a new instance of the WebView class.

    public WebView()public WebView()Public Function WebView() As
  • WebView(Windows.UI.Xaml.Controls.WebViewExecutionMode)
    WebView(Windows.UI.Xaml.Controls.WebViewExecutionMode)
    WebView(Windows.UI.Xaml.Controls.WebViewExecutionMode)
    WebView(Windows.UI.Xaml.Controls.WebViewExecutionMode)

    Initializes a new instance of the WebView class with the specified execution mode.

    public WebView(Windows.UI.Xaml.Controls.WebViewExecutionMode executionMode)public WebView(Windows.UI.Xaml.Controls.WebViewExecutionMode executionMode)Public Function WebView(executionMode As Windows.UI.Xaml.Controls.WebViewExecutionMode) As

    Parameters

Properties

  • AllowedScriptNotifyUris
    AllowedScriptNotifyUris
    AllowedScriptNotifyUris
    AllowedScriptNotifyUris
    Note

    AllowedScriptNotifyUris is not supported in apps compiled for Windows 8.1. Instead, update the ApplicationContentUriRules section of the app manifest. For more info, see the Remarks section.

    Gets or sets a safe list of URIs that are permitted to fire ScriptNotify events to this WebView.

    public IVector<Uri> AllowedScriptNotifyUris { get; set; }public IVector<Uri> AllowedScriptNotifyUris { get; set; }Public ReadWrite Property AllowedScriptNotifyUris As IVector<Uri>

    Property Value

    • The safe list of URIs that are permitted to fire ScriptNotify events.

    Remarks

    Windows 8.1

    AllowedScriptNotifyUris is not supported in apps compiled for Windows 8.1. To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the ApplicationContentUriRules section of the app manifest. (You can do this in Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS, and may contain subdomain wildcards (for example, https://.microsoft.com) but they cannot contain domain wildcards (for example, https://.com and https://.). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString(System.String).

    Windows 8

    These remarks apply only to apps compiled for Windows 8, even when running on Windows 8.1.

    To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the list returned by the AllowedScriptNotifyUris property. Set this property to AnyScriptNotifyUri to indicate that any page can fire ScriptNotify events for this WebView control. This requirement does not apply to content loaded using the NavigateToString(System.String) method.

  • AllowedScriptNotifyUrisProperty
    AllowedScriptNotifyUrisProperty
    AllowedScriptNotifyUrisProperty
    AllowedScriptNotifyUrisProperty
    Note

    AllowedScriptNotifyUrisProperty is not supported in apps compiled for Windows 8.1. Instead, update the ApplicationContentUriRules section of the app manifest. For more info, see the Remarks section.

    Identifies the AllowedScriptNotifyUris dependency property.

    public static DependencyProperty AllowedScriptNotifyUrisProperty { get; }public static DependencyProperty AllowedScriptNotifyUrisProperty { get; }Public Static ReadOnly Property AllowedScriptNotifyUrisProperty As DependencyProperty

    Property Value

    Remarks

    Windows 8.1

    AllowedScriptNotifyUrisProperty is not supported in apps compiled for Windows 8.1. To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the ApplicationContentUriRules section of the app manifest. (You can do this in Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS, and may contain subdomain wildcards (for example, https://.microsoft.com) but they cannot contain domain wildcards (for example, https://.com and https://.). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString(System.String).

    Windows 8

    These remarks apply only to apps compiled for Windows 8, even when running on Windows 8.1.

    To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the list returned by the AllowedScriptNotifyUris property. Set this property to AnyScriptNotifyUri to indicate that any page can fire ScriptNotify events for this WebView control. This requirement does not apply to content loaded using the NavigateToString(System.String) method.

  • AnyScriptNotifyUri
    AnyScriptNotifyUri
    AnyScriptNotifyUri
    AnyScriptNotifyUri
    Note

    AnyScriptNotifyUri is not supported in apps compiled for Windows 8.1. Instead, update the ApplicationContentUriRules section of the app manifest. For more info, see the Remarks section.

    Gets a value that you can use to set the AllowedScriptNotifyUris property to indicate that any page can fire ScriptNotify events to this WebView.

    public static IVector<Uri> AnyScriptNotifyUri { get; }public static IVector<Uri> AnyScriptNotifyUri { get; }Public Static ReadOnly Property AnyScriptNotifyUri As IVector<Uri>

    Property Value

    • The safe list of URIs that are permitted to fire ScriptNotify events.

    Remarks

    Windows 8.1

    AnyScriptNotifyUri is not supported in apps compiled for Windows 8.1. To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the ApplicationContentUriRules section of the app manifest. (You can do this in Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS, and may contain subdomain wildcards (for example, https://.microsoft.com) but they cannot contain domain wildcards (for example, https://.com and https://.). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString(System.String).

    Windows 8

    These remarks apply only to apps compiled for Windows 8, even when running on Windows 8.1.

    To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the list returned by the AllowedScriptNotifyUris property. Set this property to AnyScriptNotifyUri to indicate that any page can fire ScriptNotify events for this WebView control. This requirement does not apply to content loaded using the NavigateToString(System.String) method.

  • CanGoBack
    CanGoBack
    CanGoBack
    CanGoBack

    Gets a value that indicates whether there is at least one page in the backward navigation history.

    public bool CanGoBack { get; }public bool CanGoBack { get; }Public ReadOnly Property CanGoBack As bool

    Property Value

    • bool
      bool
      bool

      true if the WebView can navigate backward; otherwise, false.

    Remarks

    To navigate backward, call the GoBack() method.

  • CanGoBackProperty
    CanGoBackProperty
    CanGoBackProperty
    CanGoBackProperty

    Identifies the CanGoBack dependency property.

    public static DependencyProperty CanGoBackProperty { get; }public static DependencyProperty CanGoBackProperty { get; }Public Static ReadOnly Property CanGoBackProperty As DependencyProperty

    Property Value

  • CanGoForward
    CanGoForward
    CanGoForward
    CanGoForward

    Gets a value that indicates whether there is at least one page in the forward navigation history.

    public bool CanGoForward { get; }public bool CanGoForward { get; }Public ReadOnly Property CanGoForward As bool

    Property Value

    • bool
      bool
      bool

      true if the WebView can navigate forward; otherwise, false.

    Remarks

    To navigate forward, call the GoForward() method.

  • CanGoForwardProperty
    CanGoForwardProperty
    CanGoForwardProperty
    CanGoForwardProperty

    Identifies the CanGoForward dependency property.

    public static DependencyProperty CanGoForwardProperty { get; }public static DependencyProperty CanGoForwardProperty { get; }Public Static ReadOnly Property CanGoForwardProperty As DependencyProperty

    Property Value

  • ContainsFullScreenElement
    ContainsFullScreenElement
    ContainsFullScreenElement
    ContainsFullScreenElement

    Gets a value that indicates whether the WebView contains an element that supports full screen.

    public bool ContainsFullScreenElement { get; }public bool ContainsFullScreenElement { get; }Public ReadOnly Property ContainsFullScreenElement As bool

    Property Value

    • bool
      bool
      bool

      true if the WebView contains an element that supports full screen; otherwise, false.

  • ContainsFullScreenElementProperty
    ContainsFullScreenElementProperty
    ContainsFullScreenElementProperty
    ContainsFullScreenElementProperty

    Identifies the ContainsFullScreenElement dependency property.

    public static DependencyProperty ContainsFullScreenElementProperty { get; }public static DependencyProperty ContainsFullScreenElementProperty { get; }Public Static ReadOnly Property ContainsFullScreenElementProperty As DependencyProperty

    Property Value

  • DataTransferPackage
    DataTransferPackage
    DataTransferPackage
    DataTransferPackage
    Note

    DataTransferPackage may be altered or unavailable for releases after Windows 8.1. Instead, use CaptureSelectedContentToDataPackageAsync().

    Gets a clipboard DataPackage as passed to the WebView.

    public DataPackage DataTransferPackage { get; }public DataPackage DataTransferPackage { get; }Public ReadOnly Property DataTransferPackage As DataPackage

    Property Value

    Remarks

    This property is typically used to support sharing. During a share operation, the source app puts the data being shared in a DataPackage object and sends that object to the target app for processing.

    Examples

    The following code example demonstrates how to use this property to implement sharing support.

    void SDKSample::WebViewControl::Scenario7::Share_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
    	dataTransferManager = DataTransferManager::GetForCurrentView();
    	dataRequestedToken = dataTransferManager->DataRequested += ref new TypedEventHandler<DataTransferManager^, DataRequestedEventArgs^>(this, &Scenario7::dataTransferManager_DataRequested);
    	DataTransferManager::ShowShareUI();
    }
    
    // Data requested handler
    void SDKSample::WebViewControl::Scenario7::dataTransferManager_DataRequested(DataTransferManager^ sender, DataRequestedEventArgs^ args)
    {
    	DataRequest^ request = args->Request;
    	DataPackage^ p = WebView7->DataTransferPackage;
    	
    	if (p->GetView()->Contains(StandardDataFormats::Text))
    	{
    	    p->Properties->Title = "WebView Sharing Excerpt";
    	    p->Properties->Description = "This is a snippet from the content hosted in the WebView control";
    	    request->Data = p;
    	}
    	else
    	{
    	    request->FailWithDisplayText("Nothing to share");
    	}
        dataTransferManager->DataRequested -= dataRequestedToken;
    }
    
    private void Share_Click(object sender, RoutedEventArgs e)
    {
        dataTransferManager = DataTransferManager.GetForCurrentView();
        dataTransferManager.DataRequested += dataTransferManager_DataRequested;
        DataTransferManager.ShowShareUI();
    }
    
    void dataTransferManager_DataRequested(DataTransferManager sender, DataRequestedEventArgs args)
    {
        DataRequest request = args.Request;
        DataPackage p = WebView7.DataTransferPackage;
    
        if (p.GetView().Contains(StandardDataFormats.Text))
        {
            p.Properties.Title = "WebView Sharing Excerpt";
            p.Properties.Description = "This is a snippet from the content hosted in the WebView control";
            request.Data = p;
        }
        else
        {
            request.FailWithDisplayText("Nothing to share");
        }
        dataTransferManager.DataRequested -= dataTransferManager_DataRequested;
    }
    
    Private Sub Share_Click(sender As Object, e As RoutedEventArgs)
        dataTransferManager = dataTransferManager.GetForCurrentView()
        AddHandler dataTransferManager.DataRequested, AddressOf dataTransferManager_DataRequested
        dataTransferManager.ShowShareUI()
    End Sub
    
    Private Sub dataTransferManager_DataRequested(sender As DataTransferManager, args As DataRequestedEventArgs)
        Dim request As DataRequest = args.Request
        Dim p As DataPackage = WebView7.DataTransferPackage
    
        If p.GetView().Contains(StandardDataFormats.Text) Then
            p.Properties.Title = "WebView Sharing Excerpt"
            p.Properties.Description = "This is a snippet from the content hosted in the WebView control"
            request.Data = p
        Else
            request.FailWithDisplayText("Nothing to share")
        End If
        RemoveHandler dataTransferManager.DataRequested, AddressOf dataTransferManager_DataRequested
    End Sub
    
  • DataTransferPackageProperty
    DataTransferPackageProperty
    DataTransferPackageProperty
    DataTransferPackageProperty
    Note

    DataTransferPackageProperty may be altered or unavailable for releases after Windows 8.1. Instead, use CaptureSelectedContentToDataPackageAsync().

    Identifies the DataTransferPackage dependency property.

    public static DependencyProperty DataTransferPackageProperty { get; }public static DependencyProperty DataTransferPackageProperty { get; }Public Static ReadOnly Property DataTransferPackageProperty As DependencyProperty

    Property Value

  • DefaultBackgroundColor
    DefaultBackgroundColor
    DefaultBackgroundColor
    DefaultBackgroundColor

    Gets or sets the color to use as the WebView background when the HTML content does not specify a color.

    public Color DefaultBackgroundColor { get; set; }public Color DefaultBackgroundColor { get; set; }Public ReadWrite Property DefaultBackgroundColor As Color
    <WebView DefaultBackgroundColor="predefinedColorName"/>
    - or -
    <WebView DefaultBackgroundColor="#rgb"/>
    - or -
    <WebView DefaultBackgroundColor="#argb"/>
    - or -
    <WebView DefaultBackgroundColor="#rrggbb"/>
    - or -
    <WebView DefaultBackgroundColor="#aarrggbb"/>
    - or -
    <WebView DefaultBackgroundColor="sc#scR,scG,scB"/>
    - or -
    <WebView DefaultBackgroundColor="sc#scA,scR,scG,scB"/>
    

    Property Value

  • DefaultBackgroundColorProperty
    DefaultBackgroundColorProperty
    DefaultBackgroundColorProperty
    DefaultBackgroundColorProperty

    Identifies the DefaultBackgroundColor dependency property.

    public static DependencyProperty DefaultBackgroundColorProperty { get; }public static DependencyProperty DefaultBackgroundColorProperty { get; }Public Static ReadOnly Property DefaultBackgroundColorProperty As DependencyProperty

    Property Value

  • DefaultExecutionMode
    DefaultExecutionMode
    DefaultExecutionMode
    DefaultExecutionMode

    Gets the default threading behavior of WebView instances in the current app.

    public static WebViewExecutionMode DefaultExecutionMode { get; }public static WebViewExecutionMode DefaultExecutionMode { get; }Public Static ReadOnly Property DefaultExecutionMode As WebViewExecutionMode

    Property Value

    Remarks

    The default value for the desktop device family is SameThread. The default value for all other device families is SeparateThread.

  • DeferredPermissionRequests
    DeferredPermissionRequests
    DeferredPermissionRequests
    DeferredPermissionRequests

    Gets a collection of permission requests that are waiting to be granted or denied.

    public IVector<WebViewDeferredPermissionRequest> DeferredPermissionRequests { get; }public IVector<WebViewDeferredPermissionRequest> DeferredPermissionRequests { get; }Public ReadOnly Property DeferredPermissionRequests As IVector<WebViewDeferredPermissionRequest>

    Property Value

    Remarks

    When you defer a WebViewPermissionRequest, a new WebViewDeferredPermissionRequest is created with the same Id and added to the DeferredPermissionRequests collection. When you are ready to act on the request, call the DeferredPermissionRequestById(System.UInt32) method and pass the Id of the deferred request. After you retrieve the request, you can call the Allow() method to grant the request, or call the Deny() method to deny the request.

  • DocumentTitle
    DocumentTitle
    DocumentTitle
    DocumentTitle

    Gets the title of the page currently displayed in the WebView.

    public string DocumentTitle { get; }public string DocumentTitle { get; }Public ReadOnly Property DocumentTitle As string

    Property Value

    • string
      string
      string

      The page title.

  • DocumentTitleProperty
    DocumentTitleProperty
    DocumentTitleProperty
    DocumentTitleProperty

    Identifies the DocumentTitle dependency property.

    public static DependencyProperty DocumentTitleProperty { get; }public static DependencyProperty DocumentTitleProperty { get; }Public Static ReadOnly Property DocumentTitleProperty As DependencyProperty

    Property Value

  • ExecutionMode
    ExecutionMode
    ExecutionMode
    ExecutionMode

    Gets a value that indicates whether the WebView hosts content on the UI thread or a non-UI thread.

    public WebViewExecutionMode ExecutionMode { get; }public WebViewExecutionMode ExecutionMode { get; }Public ReadOnly Property ExecutionMode As WebViewExecutionMode

    Property Value

    Remarks

    To create a WebView with a specific ExecutionMode, use the @Windows.UI.Xaml.Controls.WebView.#ctor(Windows.UI.Xaml.Controls.WebViewExecutionMode) constructor.

    When the ExecutionMode is SameThread, WebView content is hosted on the UI thread. When the value is SeparateThread, content is hosted on a background thread.

    When the WebView is not on the UI thread, the behaviors listed here are not supported:

    • Scroll chaining and pointer chaining. (Input events aren't propagated to parent controls that uses DirectManipulation like ScrollViewer or @Windows.UI.Xaml.Controls.FlipView.)
    • Tab navigation to escape focus on WebView.
    • Printing.
  • Settings
    Settings
    Settings
    Settings

    Gets a WebViewSettings object that contains properties to enable or disable WebView features.

    public WebViewSettings Settings { get; }public WebViewSettings Settings { get; }Public ReadOnly Property Settings As WebViewSettings

    Property Value

    Remarks

    Use the WebViewSettings object to enable or disable the use of JavaScript and IndexedDB in the WebView. See IsIndexedDBEnabled and IsJavaScriptEnabled.

  • Source
    Source
    Source
    Source

    Gets or sets the Uniform Resource Identifier (URI) source of the HTML content to display in the WebView control.

    public Uri Source { get; set; }public Uri Source { get; set; }Public ReadWrite Property Source As Uri
    <WebView Source="uriString"/>
    

    Property Value

    • The Uniform Resource Identifier (URI) source of the HTML content to display in the WebView control.

    Remarks

    The Source property retains its old value during navigation until the navigation is complete. During navigation, you can get the new Uniform Resource Identifier (URI) through the event arguments for the navigation events.

  • SourceProperty
    SourceProperty
    SourceProperty
    SourceProperty

    Identifies the Source dependency property.

    public static DependencyProperty SourceProperty { get; }public static DependencyProperty SourceProperty { get; }Public Static ReadOnly Property SourceProperty As DependencyProperty

    Property Value

  • XYFocusDown
    XYFocusDown
    XYFocusDown
    XYFocusDown

    Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) down.

    public DependencyObject XYFocusDown { get; set; }public DependencyObject XYFocusDown { get; set; }Public ReadWrite Property XYFocusDown As DependencyObject
    <WebView XYFocusDown="{x:Bind dependencyObjectValue}"/>
    

    Property Value

    Remarks

    XYFocusDown is supported only on the Xbox device family, and only when using a game pad or remote control. The property is ignored otherwise.

    For more info about this property, see the XY focus navigation and interaction section of the Designing for Xbox and TV article.

    Version compatibility

    The XYFocusDown property is not available prior to Windows 10, version 1607. If your app’s 'minimum platform version' setting in Microsoft Visual Studio is less than the 'introduced version' shown in the Requirements block later in this page, you must design and test your app to account for this. For more info, see Version adaptive code.

    To avoid exceptions when your app runs on previous versions of Windows 10, do not set this property in XAML or use it without performing a runtime check. This example shows how to use the ApiInformation class to check for the presence of this property before you set it.

    
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.WebView", "XYFocusDown"))
    {
        webView1.XYFocusDown = button1;
    }
    
  • XYFocusDownProperty
    XYFocusDownProperty
    XYFocusDownProperty
    XYFocusDownProperty

    Identifies the XYFocusDown dependency property.

    public static DependencyProperty XYFocusDownProperty { get; }public static DependencyProperty XYFocusDownProperty { get; }Public Static ReadOnly Property XYFocusDownProperty As DependencyProperty

    Property Value

  • XYFocusLeft
    XYFocusLeft
    XYFocusLeft
    XYFocusLeft

    Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) left.

    public DependencyObject XYFocusLeft { get; set; }public DependencyObject XYFocusLeft { get; set; }Public ReadWrite Property XYFocusLeft As DependencyObject
    <WebView XYFocusLeft="{x:Bind dependencyObjectValue}"/>
    

    Property Value

    Remarks

    XYFocusLeft is supported only on the Xbox device family, and only when using a game pad or remote control. The property is ignored otherwise.

    For more info about this property, see the XY focus navigation and interaction section of the Designing for Xbox and TV article.

    Version compatibility

    The XYFocusLeft property is not available prior to Windows 10, version 1607. If your app’s 'minimum platform version' setting in Microsoft Visual Studio is less than the 'introduced version' shown in the Requirements block later in this page, you must design and test your app to account for this. For more info, see Version adaptive code.

    To avoid exceptions when your app runs on previous versions of Windows 10, do not set this property in XAML or use it without performing a runtime check. This example shows how to use the ApiInformation class to check for the presence of this property before you set it.

    
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.WebView", "XYFocusLeft"))
    {
        webView1.XYFocusLeft = button1;
    }
    
  • XYFocusLeftProperty
    XYFocusLeftProperty
    XYFocusLeftProperty
    XYFocusLeftProperty

    Identifies the XYFocusLeft dependency property.

    public static DependencyProperty XYFocusLeftProperty { get; }public static DependencyProperty XYFocusLeftProperty { get; }Public Static ReadOnly Property XYFocusLeftProperty As DependencyProperty

    Property Value

  • XYFocusRight
    XYFocusRight
    XYFocusRight
    XYFocusRight

    Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) right.

    public DependencyObject XYFocusRight { get; set; }public DependencyObject XYFocusRight { get; set; }Public ReadWrite Property XYFocusRight As DependencyObject
    <WebView XYFocusRight="{x:Bind dependencyObjectValue}"/>
    

    Property Value

    Remarks

    XYFocusRight is supported only on the Xbox device family, and only when using a game pad or remote control. The property is ignored otherwise.

    For more info about this property, see the XY focus navigation and interaction section of the Designing for Xbox and TV article.

    Version compatibility

    The XYFocusRight property is not available prior to Windows 10, version 1607. If your app’s 'minimum platform version' setting in Microsoft Visual Studio is less than the 'introduced version' shown in the Requirements block later in this page, you must design and test your app to account for this. For more info, see Version adaptive code.

    To avoid exceptions when your app runs on previous versions of Windows 10, do not set this property in XAML or use it without performing a runtime check. This example shows how to use the ApiInformation class to check for the presence of this property before you set it.

    
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.WebView", "XYFocusRight"))
    {
        webView1.XYFocusRight = button1;
    }
    
  • XYFocusRightProperty
    XYFocusRightProperty
    XYFocusRightProperty
    XYFocusRightProperty

    Identifies the XYFocusRight dependency property.

    public static DependencyProperty XYFocusRightProperty { get; }public static DependencyProperty XYFocusRightProperty { get; }Public Static ReadOnly Property XYFocusRightProperty As DependencyProperty

    Property Value

  • XYFocusUp
    XYFocusUp
    XYFocusUp
    XYFocusUp

    Gets or sets the object that gets focus when a user presses the Directional Pad (D-pad) up.

    public DependencyObject XYFocusUp { get; set; }public DependencyObject XYFocusUp { get; set; }Public ReadWrite Property XYFocusUp As DependencyObject
    <WebView XYFocusUp="{x:Bind dependencyObjectValue}"/>
    

    Property Value

    Remarks

    XYFocusUp is supported only on the Xbox device family, and only when using a game pad or remote control. The property is ignored otherwise.

    For more info about this property, see the XY focus navigation and interaction section of the Designing for Xbox and TV article.

    Version compatibility

    The XYFocusUp property is not available prior to Windows 10, version 1607. If your app’s 'minimum platform version' setting in Microsoft Visual Studio is less than the 'introduced version' shown in the Requirements block later in this page, you must design and test your app to account for this. For more info, see Version adaptive code.

    To avoid exceptions when your app runs on previous versions of Windows 10, do not set this property in XAML or use it without performing a runtime check. This example shows how to use the ApiInformation class to check for the presence of this property before you set it.

    
    if (ApiInformation.IsPropertyPresent("Windows.UI.Xaml.Controls.WebView", "XYFocusUp"))
    {
        webView1.XYFocusUp = button1;
    }
    
  • XYFocusUpProperty
    XYFocusUpProperty
    XYFocusUpProperty
    XYFocusUpProperty

    Identifies the XYFocusUp dependency property.

    public static DependencyProperty XYFocusUpProperty { get; }public static DependencyProperty XYFocusUpProperty { get; }Public Static ReadOnly Property XYFocusUpProperty As DependencyProperty

    Property Value

Methods

  • AddWebAllowedObject(System.String,System.Object)
    AddWebAllowedObject(System.String,System.Object)
    AddWebAllowedObject(System.String,System.Object)
    AddWebAllowedObject(System.String,System.Object)

    Adds a native Windows Runtime object as a global parameter to the top level document inside of a WebView.

    public void AddWebAllowedObject(System.String name,System.Object pObject)public void AddWebAllowedObject(System.String name,System.Object pObject)Public Function AddWebAllowedObject(name As System.String,pObject As System.Object) As void

    Parameters

    • name
      System.String
      System.String
      System.String

      The name of the object to expose to the document in the WebView.

    • pObject
      System.Object
      System.Object
      System.Object

      The object to expose to the document in the WebView.

    Remarks

    Use this method to expose a native Windows Runtime object as a global parameter in the context of the top level document inside of a WebView. For a Windows Runtime object to be projected, it must agile and be decorated with the AllowForWeb attribute.

    Note

    Runtime classes created using Microsoft Visual Basic, C# or Visual C++ component extensions (C++/CX) are agile by default. For more info, see Threading and Marshaling and Using Windows Runtime objects in a multithreaded environment.

    The object passed into AddWebAllowedObject(System.String,System.Object) must be imported from a Windows Runtime component that is separate from the app assembly. This is necessary for the AllowForWeb attribute to be property identified by the WebView security subsystem. If you use a class from your app project, AddWebAllowedObject(System.String,System.Object) does not work.

    You must call AddWebAllowedObject(System.String,System.Object) every time WebView is navigated to a new page that accesses the native object. You can use the NavigationStarting event to inject the object when navigation begins.

    Examples

    This example shows how to decorate a class with the AllowForWeb attribute.

    using Windows.Foundation.Metadata;
    
    namespace MyRuntimeComponent
    {
        [AllowForWeb]
        public sealed class MyNativeClass
        {
            public void NativeMethod()
            {
                ...
            }
    
            ...
        }
    }
    

    This example demonstrates using the NavigationStarting event to inject an object when navigation begins.

    <WebView x:Name="webView" Source="https://www.contoso.com/index.html"
             NavigationStarting="webView_NavigationStarting"/>
    
    private void webView_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args) 
    { 
        if (args.Uri.Host == "www.contoso.com")  
        { 
            webView.AddWebAllowedObject("nativeObject", new MyNativeClass()); 
        } 
    }
    

    Here's how to access the native object in a script in the web page.

    <script type='text/javascript'>
        nativeObject.nativeMethod(); // Call the projected WinRT method.
    </script>
    
  • BuildLocalStreamUri(System.String,System.String)
    BuildLocalStreamUri(System.String,System.String)
    BuildLocalStreamUri(System.String,System.String)
    BuildLocalStreamUri(System.String,System.String)

    Creates a URI that you can pass to NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver).

    public Uri BuildLocalStreamUri(System.String contentIdentifier,System.String relativePath)public Uri BuildLocalStreamUri(System.String contentIdentifier,System.String relativePath)Public Function BuildLocalStreamUri(contentIdentifier As System.String,relativePath As System.String) As Uri

    Parameters

    • contentIdentifier
      System.String
      System.String
      System.String

      A unique identifier for the content the URI is referencing. This defines the root of the URI.

    • relativePath
      System.String
      System.String
      System.String

      The path to the resource, relative to the root.

    Returns

    • The URI created by combining and normalizing the contentIdentifier and relativePath.

    Remarks

    Examples

    The following code example shows how to use this method with a resolver that will serve a file from the app package. For a complete example, see the XAML WebView control sample.

    
    public sealed partial class TestPage : Page
    {
        // ... other code ...
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // The 'Host' part of the URI for the ms-local-stream protocol needs to be a combination of the package name
            // and an application-defined key, which identifies the specific resolver, in this case 'MyTag'.
    
            Uri url = webView4.BuildLocalStreamUri("MyTag","/Minesweeper/default.html");
            StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
    
            // Pass the resolver object to the navigate call.
            webView4.NavigateToLocalStreamUri(url, myResolver);
        }
    }
    
    public sealed class StreamUriWinRTResolver : IUriToStreamResolver
    {
        public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
        {
            if (uri == null)
            {
                throw new Exception();
            }
            string path = uri.AbsolutePath;
    
            // Because of the signature of the this method, it can't use await, so we 
            // call into a seperate helper method that can use the C# await pattern.
            return GetContent(path).AsAsyncOperation();
        }
    
        private async Task<IInputStream> GetContent(string path)
        {
            // We use a package folder as the source, but the same principle should apply
            // when supplying content from other locations
            try
            {
                Uri localUri= new Uri("ms-appx:///html" + path);
                StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
                IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
                return stream.GetInputStreamAt(0);
            }
            catch (Exception) { throw new Exception("Invalid path"); }
        }
    }
    
  • CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream)
    CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream)
    CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream)
    CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream)

    Creates an image of the current WebView contents and writes it to the specified stream.

    public IAsyncAction CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream stream)public IAsyncAction CapturePreviewToStreamAsync(Windows.Storage.Streams.IRandomAccessStream stream)Public Function CapturePreviewToStreamAsync(stream As Windows.Storage.Streams.IRandomAccessStream) As IAsyncAction

    Parameters

    Returns

    Remarks

    Examples

    This example shows how to use this method to create a thumbnail image of the current content. For the complete example, see the WebView control sample.

    private async void bookmarkBtn_Click(object sender, RoutedEventArgs e)
    {
        InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream();
        await webView8.CapturePreviewToStreamAsync(ms);
    
        // Create a small thumbnail.
        int longlength = 180, width = 0, height = 0;
        double srcwidth = webView8.ActualWidth, srcheight = webView8.ActualHeight;
        double factor = srcwidth / srcheight;
        if (factor < 1)
        {
            height = longlength;
            width = (int)(longlength * factor);
        }
        else
        {
            width = longlength;
            height = (int)(longlength / factor);
        }
        BitmapSource small = await resize(width, height, ms);
    
        BookmarkItem item = new BookmarkItem();
        item.Title = webView8.DocumentTitle;
        item.PageUrl = webView8.Source;
        item.Preview = small;
    
        bookmarks.Add(item);
    }
    
  • CaptureSelectedContentToDataPackageAsync()
    CaptureSelectedContentToDataPackageAsync()
    CaptureSelectedContentToDataPackageAsync()
    CaptureSelectedContentToDataPackageAsync()

    Asynchronously gets a DataPackage that contains the selected content within the WebView.

    public IAsyncOperation<DataPackage> CaptureSelectedContentToDataPackageAsync()public IAsyncOperation<DataPackage> CaptureSelectedContentToDataPackageAsync()Public Function CaptureSelectedContentToDataPackageAsync() As IAsyncOperation( Of DataPackage )

    Returns

    • When this method completes, it returns the selected content as a DataPackage.

    Remarks

    You can use this method during a share operation to send the selected WebView content to a target app. This method is asynchronous, so you must use a deferral to prevent your DataRequested event handler from returning before the asynchronous call is complete. Call GetDeferral() to create the deferral and Complete() to end it.

  • ClearTemporaryWebDataAsync()
    ClearTemporaryWebDataAsync()
    ClearTemporaryWebDataAsync()
    ClearTemporaryWebDataAsync()

    Clears the WebView 's cache and IndexedDB data.

    public static IAsyncAction ClearTemporaryWebDataAsync()public static IAsyncAction ClearTemporaryWebDataAsync()Public Static Function ClearTemporaryWebDataAsync() As IAsyncAction

    Returns

  • DeferredPermissionRequestById(System.UInt32)
    DeferredPermissionRequestById(System.UInt32)
    DeferredPermissionRequestById(System.UInt32)
    DeferredPermissionRequestById(System.UInt32)

    Returns the deferred permission request with the specified Id.

    public WebViewDeferredPermissionRequest DeferredPermissionRequestById(System.UInt32 id)public WebViewDeferredPermissionRequest DeferredPermissionRequestById(System.UInt32 id)Public Function DeferredPermissionRequestById(id As System.UInt32) As WebViewDeferredPermissionRequest

    Parameters

    • id
      System.UInt32
      System.UInt32
      System.UInt32

      The Id of the deferred permission request.

    Returns

    Remarks

    When you defer a WebViewPermissionRequest, a new WebViewDeferredPermissionRequest is created with the same Id and added to the DeferredPermissionRequests collection. When you are ready to act on the request, call the DeferredPermissionRequestById(System.UInt32) method and pass the Id of the deferred request. After you retrieve the request, you can call the Allow() method to grant the request, or call the Deny() method to deny the request.

  • Focus(Windows.UI.Xaml.FocusState)
    Focus(Windows.UI.Xaml.FocusState)
    Focus(Windows.UI.Xaml.FocusState)
    Focus(Windows.UI.Xaml.FocusState)

    Sets the input focus to the WebView.

    public bool Focus(Windows.UI.Xaml.FocusState value)public bool Focus(Windows.UI.Xaml.FocusState value)Public Function Focus(value As Windows.UI.Xaml.FocusState) As bool

    Parameters

    Returns

    • bool
      bool
      bool

      true if focus was set; otherwise, false.

    Remarks

    In apps compiled for Windows 8, the WebView control automatically gets input focus whenever you use script to programmatically set the focus to some content in the WebView. In apps compiled for Windows 8.1, this does not occur automatically. Instead, you must call the Focus(Windows.UI.Xaml.FocusState) method to set the focus to the WebView control and also use script to set the focus to some content in the control.

    When you call this method, you will typically pass in a FocusState value of Programmatic. Use the Pointer and Keyboard values when you call this method in response to direct user input. You cannot use this method to remove input focus from the control. The Unfocused value will throw an exception.

  • GoBack()
    GoBack()
    GoBack()
    GoBack()

    Navigates the WebView to the previous page in the navigation history.

    public void GoBack()public void GoBack()Public Function GoBack() As void
  • GoForward()
    GoForward()
    GoForward()
    GoForward()

    Navigates the WebView to the next page in the navigation history.

    public void GoForward()public void GoForward()Public Function GoForward() As void
  • InvokeScript(System.String,System.String[])
    InvokeScript(System.String,System.String[])
    InvokeScript(System.String,System.String[])
    InvokeScript(System.String,System.String[])

    Executes the specified script function from the currently loaded HTML, with specific arguments.

    public string InvokeScript(System.String scriptName,System.String[] arguments)public string InvokeScript(System.String scriptName,System.String[] arguments)Public Function InvokeScript(scriptName As System.String,arguments As System.String[]) As string

    Parameters

    • scriptName
      System.String
      System.String
      System.String

      The name of the script function to invoke.

    • arguments
      System.String[]
      System.String[]
      System.String[]

      A string array that packages arguments to the script function.

    Returns

    • string
      string
      string

      The result of the script invocation.

    Remarks

    The invoked script can return only string values.

  • InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String})
    InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String})
    InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String})
    InvokeScriptAsync(System.String,Windows.Foundation.Collections.IIterable{System.String})

    Executes the specified script function from the currently loaded HTML, with specific arguments, as an asynchronous action.

    public IAsyncOperation<string> InvokeScriptAsync(System.String scriptName,Windows.Foundation.Collections.IIterable{System.String} arguments)public IAsyncOperation<string> InvokeScriptAsync(System.String scriptName,Windows.Foundation.Collections.IIterable{System.String} arguments)Public Function InvokeScriptAsync(scriptName As System.String,arguments As Windows.Foundation.Collections.IIterable{System.String}) As IAsyncOperation( Of string )

    Parameters

    • scriptName
      System.String
      System.String
      System.String

      The name of the script function to invoke.

    • arguments

      A string array that packages arguments to the script function.

    Returns

    • When this method returns, the string result of the script invocation.

    Remarks

    To prevent malicious code from exploiting your app, be sure to call this method to invoke only scripts that you trust.

    The invoked script can return only string values.

    Your app might appear unresponsive while scripts are running. Handle the LongRunningScriptDetected event to interrupt a long-running script.

  • Navigate(Windows.Foundation.Uri)
    Navigate(Windows.Foundation.Uri)
    Navigate(Windows.Foundation.Uri)
    Navigate(Windows.Foundation.Uri)

    Loads the HTML content at the specified Uniform Resource Identifier (URI).

    public void Navigate(Windows.Foundation.Uri source)public void Navigate(Windows.Foundation.Uri source)Public Function Navigate(source As Windows.Foundation.Uri) As void

    Parameters

    • source

      The Uniform Resource Identifier (URI) to load.

  • NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver)
    NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver)
    NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver)
    NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver)

    Loads local web content at the specified URI using an IUriToStreamResolver.

    public void NavigateToLocalStreamUri(Windows.Foundation.Uri source,Windows.Web.IUriToStreamResolver streamResolver)public void NavigateToLocalStreamUri(Windows.Foundation.Uri source,Windows.Web.IUriToStreamResolver streamResolver)Public Function NavigateToLocalStreamUri(source As Windows.Foundation.Uri,streamResolver As Windows.Web.IUriToStreamResolver) As void

    Parameters

    Remarks

    Use this method to load local content that the NavigateToString(System.String) method won't handle. NavigateToString(System.String) provides an easy way to navigate to static HTML content, including content with references to resources such as CSS, scripts, images, and fonts. However, NavigateToString(System.String) does not provide a way to generate these resources programmatically.

    To use the NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver) method, you must pass in an IUriToStreamResolver implementation that translates a URI pattern into a content stream. You can do this to supply the content for all the resources used by a web page, or series of pages. For example, you can use this method to display content saved on the local file system as encrypted files or in cab packages. When the content is requested, you can use an IUriToStreamResolver implementation to decrypt it on the fly.

    The IUriToStreamResolver interface has one method, UriToStreamAsync(Windows.Foundation.Uri) which takes the URI and returns the stream. The URI is in the form of “ms-local-stream://appname_KEY/folder/file” where KEY identifies the resolver. Use BuildLocalStreamUri(System.String,System.String) to create a URI in the correct format that references the local content to load.

    Note

    Your IUriToStreamResolver implementation must be agile to prevent deadlock that can occur when the UI thread waits for the IUriToStreamResolver to finish its work before continuing. For more info, see Threading and Marshaling.

    Examples

    The following code example shows how to create and use a resolver that will serve a file from the app package. For a complete example, see the XAML WebView control sample.

    
    public sealed partial class TestPage : Page
    {
        // ... other code ...
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // The 'Host' part of the URI for the ms-local-stream protocol needs to be a combination of the package name
            // and an application-defined key, which identifies the specific resolver, in this case 'MyTag'.
    
            Uri url = webView4.BuildLocalStreamUri("MyTag","/Minesweeper/default.html");
            StreamUriWinRTResolver myResolver = new StreamUriWinRTResolver();
    
            // Pass the resolver object to the navigate call.
            webView4.NavigateToLocalStreamUri(url, myResolver);
        }
    }
    
    public sealed class StreamUriWinRTResolver : IUriToStreamResolver
    {
        public IAsyncOperation<IInputStream> UriToStreamAsync(Uri uri)
        {
            if (uri == null)
            {
                throw new Exception();
            }
            string path = uri.AbsolutePath;
    
            // Because of the signature of the this method, it can't use await, so we 
            // call into a seperate helper method that can use the C# await pattern.
            return GetContent(path).AsAsyncOperation();
        }
    
        private async Task<IInputStream> GetContent(string path)
        {
            // We use a package folder as the source, but the same principle should apply
            // when supplying content from other locations
            try
            {
                Uri localUri= new Uri("ms-appx:///html" + path);
                StorageFile f = await StorageFile.GetFileFromApplicationUriAsync(localUri);
                IRandomAccessStream stream = await f.OpenAsync(FileAccessMode.Read);
                return stream;
            }
            catch (Exception) { throw new Exception("Invalid path"); }
        }
    }
    
  • NavigateToString(System.String)
    NavigateToString(System.String)
    NavigateToString(System.String)
    NavigateToString(System.String)

    Loads the specified HTML content as a new document.

    public void NavigateToString(System.String text)public void NavigateToString(System.String text)Public Function NavigateToString(text As System.String) As void

    Parameters

    • text
      System.String
      System.String
      System.String

      The HTML content to display in the WebView control.

    Remarks

    NavigateToString(System.String) is asynchronous. Use the NavigationCompleted event to detect when navigation has completed.

    Note

    NavigationCompleted replaces LoadCompleted starting with Windows 8.1. In apps compiled for Windows 8, use LoadCompleted instead.

    NavigateToString(System.String) supports content with references to external files such as CSS, scripts, images, and fonts. However, it does not provide a way to generate or provide these resources programmatically. Windows 8.1 introduces NavigateToLocalStreamUri(Windows.Foundation.Uri,Windows.Web.IUriToStreamResolver) to provide this support.

  • NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage)
    NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage)
    NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage)
    NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage)

    Navigates the WebView to a URI with a POST request and HTTP headers.

    public void NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage requestMessage)public void NavigateWithHttpRequestMessage(Windows.Web.Http.HttpRequestMessage requestMessage)Public Function NavigateWithHttpRequestMessage(requestMessage As Windows.Web.Http.HttpRequestMessage) As void

    Parameters

    Remarks

    This method supports only Post and Get for the Method property value.

    Warning

    If you add additional headers to this request, such as authentication credentials, remember that those headers will also be included with any subsequent child requests. Use caution to prevent accidental disclosure of confidential or personal information.

    Examples

    This example shows how to create an HTTP request and use it with this method.

    HttpRequestMessage httpRequestMessage = new HttpRequestMessage(
        HttpMethod.Post, new Uri("http://www.contoso.com"));
    httpRequestMessage.Content = new HttpStringContent("hello, world");
    httpRequestMessage.Headers.Append("X-My-Client","true");
    
    myWebView.NavigateWithHttpRequestMessage(httpRequestMessage);
    
  • Refresh()
    Refresh()
    Refresh()
    Refresh()

    Reloads the current content in the WebView.

    public void Refresh()public void Refresh()Public Function Refresh() As void

    Remarks

    If the current content was loaded via an HTTP URI, this method reloads the file without forced cache validation by sending a "Pragma:no-cache" header to the server.

  • Stop()
    Stop()
    Stop()
    Stop()

    Halts the current WebView navigation or download.

    public void Stop()public void Stop()Public Function Stop() As void

Events

  • ContainsFullScreenElementChanged
    ContainsFullScreenElementChanged
    ContainsFullScreenElementChanged
    ContainsFullScreenElementChanged

    Occurs when the status of whether the WebView currently contains a full screen element or not changes.

    public event TypedEventHandler ContainsFullScreenElementChangedpublic event TypedEventHandler ContainsFullScreenElementChangedPublic Event ContainsFullScreenElementChanged
    <WebView ContainsFullScreenElementChanged="eventhandler"/>
    
    
  • ContentLoading
    ContentLoading
    ContentLoading
    ContentLoading

    Occurs when the WebView has started loading new content.

    public event TypedEventHandler ContentLoadingpublic event TypedEventHandler ContentLoadingPublic Event ContentLoading
    <WebView ContentLoading="eventhandler"/>
    
    

    Remarks

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • DOMContentLoaded
    DOMContentLoaded
    DOMContentLoaded
    DOMContentLoaded

    Occurs when the WebView has finished parsing the current HTML content.

    public event TypedEventHandler DOMContentLoadedpublic event TypedEventHandler DOMContentLoadedPublic Event DOMContentLoaded
    <WebView DOMContentLoaded="eventhandler"/>
    
    

    Remarks

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • FrameContentLoading
    FrameContentLoading
    FrameContentLoading
    FrameContentLoading

    Occurs when a frame in the WebView has started loading new content.

    public event TypedEventHandler FrameContentLoadingpublic event TypedEventHandler FrameContentLoadingPublic Event FrameContentLoading
    <WebView FrameContentLoading="eventhandler"/>
    
    

    Remarks

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • FrameDOMContentLoaded
    FrameDOMContentLoaded
    FrameDOMContentLoaded
    FrameDOMContentLoaded

    Occurs when a frame in the WebView has finished parsing its current HTML content.

    public event TypedEventHandler FrameDOMContentLoadedpublic event TypedEventHandler FrameDOMContentLoadedPublic Event FrameDOMContentLoaded
    <WebView FrameDOMContentLoaded="eventhandler"/>
    
    

    Remarks

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • FrameNavigationCompleted
    FrameNavigationCompleted
    FrameNavigationCompleted
    FrameNavigationCompleted

    Occurs when a frame in the WebView has finished loading its content.

    public event TypedEventHandler FrameNavigationCompletedpublic event TypedEventHandler FrameNavigationCompletedPublic Event FrameNavigationCompleted
    <WebView FrameNavigationCompleted="eventhandler"/>
    
    

    Remarks

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • FrameNavigationStarting
    FrameNavigationStarting
    FrameNavigationStarting
    FrameNavigationStarting

    Occurs before a frame in the WebView navigates to new content.

    public event TypedEventHandler FrameNavigationStartingpublic event TypedEventHandler FrameNavigationStartingPublic Event FrameNavigationStarting
    <WebView FrameNavigationStarting="eventhandler"/>
    
    

    Remarks

    You can cancel navigation in a handler for this event by setting the Cancel property to true.

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • LoadCompleted
    LoadCompleted
    LoadCompleted
    LoadCompleted
    Note

    LoadCompleted may be altered or unavailable for releases after Windows 8.1. Instead, use NavigationCompleted.

    Occurs when top-level navigation completes and the content loads into the WebView control or when an error occurs during loading.

    public event LoadCompletedEventHandler LoadCompletedpublic event LoadCompletedEventHandler LoadCompletedPublic Event LoadCompleted
    <WebView LoadCompleted="eventhandler"/>
    
    
  • LongRunningScriptDetected
    LongRunningScriptDetected
    LongRunningScriptDetected
    LongRunningScriptDetected

    Occurs periodically while the WebView executes JavaScript, letting you halt the script.

    public event TypedEventHandler LongRunningScriptDetectedpublic event TypedEventHandler LongRunningScriptDetectedPublic Event LongRunningScriptDetected
    <WebView LongRunningScriptDetected="eventhandler"/>
    
    

    Remarks

    Your app might appear unresponsive while scripts are running. This event provides an opportunity to interrupt a long-running script. To determine how long the script has been running, check the ExecutionTime property of the WebViewLongRunningScriptDetectedEventArgs object. To halt the script, set the event args StopPageScriptExecution property to true. The halted script will not execute again unless it is reloaded during a subsequent WebView navigation.

    Note

    In some cases, the WebView cannot detect a long-running script. For example, this event might not occur if the script is stuck in a loop that doesn’t perform any memory allocations.

  • NavigationCompleted
    NavigationCompleted
    NavigationCompleted
    NavigationCompleted

    Occurs when the WebView has finished loading the current content or if navigation has failed.

    public event TypedEventHandler NavigationCompletedpublic event TypedEventHandler NavigationCompletedPublic Event NavigationCompleted
    <WebView NavigationCompleted="eventhandler"/>
    
    

    Remarks

    To determine whether navigation has failed, check the IsSuccess and WebErrorStatus properties of the WebViewNavigationCompletedEventArgs class.

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

  • NavigationFailed
    NavigationFailed
    NavigationFailed
    NavigationFailed
    Note

    NavigationFailed may be altered or unavailable for releases after Windows 8.1. Instead, use NavigationCompleted.

    Occurs when the WebView cannot complete the navigation attempt.

    public event WebViewNavigationFailedEventHandler NavigationFailedpublic event WebViewNavigationFailedEventHandler NavigationFailedPublic Event NavigationFailed
    <WebView NavigationFailed="eventhandler" />
    
  • NavigationStarting
    NavigationStarting
    NavigationStarting
    NavigationStarting

    Occurs before the WebView navigates to new content.

    public event TypedEventHandler NavigationStartingpublic event TypedEventHandler NavigationStartingPublic Event NavigationStarting
    <WebView NavigationStarting="eventhandler" />
    

    Remarks

    You can cancel navigation in a handler for this event by setting the Cancel property to true.

    WebView navigation events occur in the following order:

    Similar events occur in the same order for each iframe in the WebView content:

    Examples

    The following code example demonstrates how to handle this event to update a text box used as an address bar. For the complete example, see the XAML WebView control sample.

    void webView1_NavigationStarting(WebView sender, WebViewNavigationStartingEventArgs args)
    {
        string url = "";
        try { url = args.Uri.ToString(); }
        finally
        {
            address.Text = url;
            appendLog(String.Format("Starting navigation to: \"{0}\".\n", url));
            pageIsLoading = true;
        }
    }
    
  • NewWindowRequested
    NewWindowRequested
    NewWindowRequested
    NewWindowRequested

    Occurs when a user performs an action in a WebView that causes content to be opened in a new window.

    public event TypedEventHandler NewWindowRequestedpublic event TypedEventHandler NewWindowRequestedPublic Event NewWindowRequested
    <WebView NewWindowRequested="eventhandler"/>
    

    Remarks

    See WebViewNewWindowRequestedEventArgs.

    This event occurs only for user initiated actions. By default, when a user clicks a link in a WebView that requests to open in a new window, the link launches the default browser. A new window can be caused by the user clicking on an href, or a button which calls window.open.

    Handle this event to provide custom handling of the new window request. You might navigate the WebView to the desired page, or create a new WebView in your app to display the requested content. If you provide custom handling of the new window request, set the Handled property to true to prevent the default browser from being launched.

    Examples

    <WebView x:Name="myWebView" NewWindowRequested="OnNewWindowRequested" />
    
    private void OnNewWindowRequested (WebView sender, WebViewNewWindowRequestedEventArgs e) 
    { 
        if (e.Referrer.Host == "www.contoso.com") 
        { 
             var newWebView = new WebView(); 
             newWebView.Navigate(e.Uri); 
             myGrid.Children.Add(newWebView); 
             e.Handled = true; 
        } 
    }
    
  • PermissionRequested
    PermissionRequested
    PermissionRequested
    PermissionRequested

    Occurs when an action in a WebView requires that permission be granted.

    public event TypedEventHandler PermissionRequestedpublic event TypedEventHandler PermissionRequestedPublic Event PermissionRequested

    Remarks

    The types of permission that can be requested are defined in the WebViewPermissionType enumeration.

    If you don't handle the PermissionRequested event, the WebView denies permission by default.

    When you handle a permission request in a WebView, you get a WebViewPermissionRequest object as the value of the PermissionRequest property. You can call Allow() to grant the request, Deny() to deny the request, or Defer() to defer the request until a later time. For example, you might defer the request if you need to prompt the user for consent.

    When you defer a WebViewPermissionRequest, a new WebViewDeferredPermissionRequest is created with the same Id and added to the DeferredPermissionRequests collection. When you are ready to act on the request, call the DeferredPermissionRequestById(System.UInt32) method and pass the Id of the deferred request. After you retrieve the request, you can call the Allow() method to grant the request, or call the Deny() method to deny the request.

  • ScriptNotify
    ScriptNotify
    ScriptNotify
    ScriptNotify

    Occurs when the content contained in the WebView control passes a string to the application by using JavaScript.

    public event NotifyEventHandler ScriptNotifypublic event NotifyEventHandler ScriptNotifyPublic Event ScriptNotify
    <WebView ScriptNotify="eventhandler"/>
    
    

    Remarks

    A hosted HTML page can fire the ScriptNotify event in your Windows Store app when the page calls window.external.notify and passes a string parameter.

    Note

    Because this event is initiated by external code, you should be careful about what you put in the event handler. To prevent malicious scripts from exploiting this event, be sure to enable it only for trusted URIs, as described below.

    Windows 8.1

    To enable an external web page to fire the ScriptNotify event when calling window.external.notify, you must include the page's URI in the ApplicationContentUriRules section of the app manifest. (You can do this in Visual Studio on the Content URIs tab of the Package.appxmanifest designer.) The URIs in this list must use HTTPS and may contain subdomain wildcards (for example, "https://.microsoft.com"), but they can't contain domain wildcards (for example, "https://.com" and "https://."). The manifest requirement does not apply to content that originates from the app package, uses an ms-local-stream:// URI, or is loaded using NavigateToString(System.String).

    Note

    If you have more then one subdomain, you must use one wildcard for each subdomain. For example, "https://.microsoft.com" matches with "https://any.microsoft.com" but not with "https://this.any*.microsoft.com."

    These changes do not affect apps compiled for Windows 8, even when running on Windows 8.1.

    AllowedScriptNotifyUris, AnyScriptNotifyUri, and AllowedScriptNotifyUrisProperty are not supported in apps compiled for Windows 8.1.

    Windows 8

    These remarks apply only to apps compiled for Windows 8, even when running on Windows 8.1.

    If content is loaded into the WebView control using the Navigate(Windows.Foundation.Uri) method, the app must opt-in to receiving ScriptNotify events by using the AllowedScriptNotifyUris property, which has the list of URIs that can fire ScriptNotify. If the content is loaded using NavigateToString(System.String), the application will receive ScriptNotify events without the opt-in. Set the AllowedScriptNotifyUris property to the value returned by the AnyScriptNotifyUri property to indicate that any page can fire ScriptNotify events to this WebView control.

    Examples

    The following code example demonstrates the use of the ScriptNotify event in apps compiled for Windows 8. Starting with Windows 8.1, omit the lines related to AllowedScriptNotifyUris.

    public MyPage()
    {
        this.InitializeComponent();
        MyWebView.ScriptNotify += MyWebView_ScriptNotify;
    
        // Here we have to set the AllowedScriptNotifyUri property because we are 
        // navigating to some site where we don't own the content and we want to 
        // allow window.external.notify() to pass data back to the app.
        List<Uri> allowedUris = new List<Uri>();
        allowedUris.Add(new Uri("http://www.bing.com"));
        MyWebView.AllowedScriptNotifyUris = allowedUris;
    }
    
    void MyWebView_ScriptNotify(object sender, NotifyEventArgs e)
    {
        // Respond to the script notification.
    }
    
  • UnsafeContentWarningDisplaying
    UnsafeContentWarningDisplaying
    UnsafeContentWarningDisplaying
    UnsafeContentWarningDisplaying

    Occurs when the WebView shows a warning page for content that was reported as unsafe by SmartScreen Filter.

    public event TypedEventHandler UnsafeContentWarningDisplayingpublic event TypedEventHandler UnsafeContentWarningDisplayingPublic Event UnsafeContentWarningDisplaying
    <WebView UnsafeContentWarningDisplaying="eventhandler" />
    

    Remarks

    This event is not implemented on Windows Phone 8.1 and will never be raised.

    This event occurs when the warning page appears. If the user chooses to continue the navigation, subsequent navigation to the page will not display the warning nor fire the event.

  • UnsupportedUriSchemeIdentified
    UnsupportedUriSchemeIdentified
    UnsupportedUriSchemeIdentified
    UnsupportedUriSchemeIdentified

    Occurs when an attempt is made to navigate to a Uniform Resource Identifier (URI) using a scheme that WebView doesn't support.

    public event TypedEventHandler UnsupportedUriSchemeIdentifiedpublic event TypedEventHandler UnsupportedUriSchemeIdentifiedPublic Event UnsupportedUriSchemeIdentified
    <WebView UnsupportedUriSchemeIdentified="eventhandler"/>
    

    Remarks

    See WebViewUnsupportedUriSchemeIdentifiedEventArgs.

    WebView supports navigation to Uniform Resource Identifier (URI) using these schemes: http, https, ms-appx-web, and ms-local-stream.

    If an attempt is made to navigate to a Uniform Resource Identifier (URI) that the WebView doesn't support, the navigation is blocked. By default, when an unsupported Uniform Resource Identifier (URI) scheme is encountered, the launcher is invoked to find the default provider for the Uniform Resource Identifier (URI) scheme. You can handle the UnsupportedUriSchemeIdentified event to decide how to handle an unsupported Uniform Resource Identifier (URI) scheme. If you do nothing, the launcher is invoked. If you provide custom handling for the Uniform Resource Identifier (URI) scheme, set the Handled property to true to prevent the default provider for the Uniform Resource Identifier (URI) scheme from being invoked.

    Examples

    <WebView x:Name="myWebView" UnsupportedUriSchemeIdentified="OnUnsupportedUriSchemeIdentified" />
    
    private void OnUnsupportedUriSchemeIdentified (WebView sender, WebViewUnsupportedUriSchemeIdentifiedEventArgs e) 
    { 
        // Block all URIs from invoking other apps except the mailto: protocol. 
        if (e.Uri.Scheme != "mailto") 
        { 
            e.Handled= true; 
        } 
    }
    
  • UnviewableContentIdentified
    UnviewableContentIdentified
    UnviewableContentIdentified
    UnviewableContentIdentified

    Occurs when the WebView attempts to download an unsupported file.

    public event TypedEventHandler UnviewableContentIdentifiedpublic event TypedEventHandler UnviewableContentIdentifiedPublic Event UnviewableContentIdentified
    <WebView UnviewableContentIdentified="eventhandler" />
    

    Remarks

    The WebView control cannot host arbitrary file types, but you can handle this event and use the Launcher class to redirect the file to the browser or another app.

    Examples

    The following code example demonstrates how to handle this event to launch an external browser when the WebView control cannot render the target content. For the complete example, see the XAML WebView control sample.

    void webView1_UnviewableContentIdentified(WebView sender, 
        WebViewUnviewableContentIdentifiedEventArgs args)
    {
        appendLog(String.Format("Content for \"{0}\" cannot be loaded into webview. " +
            "Invoking the default launcher instead.\n", args.Uri.ToString()));
    
        // We turn around and hand the Uri to the 
        // system launcher to launch the default handler for it.
        Windows.Foundation.IAsyncOperation<bool> b = 
            Windows.System.Launcher.LaunchUriAsync(args.Uri);
        pageIsLoading = false;
    }
    

Attributes

Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.WebHostHiddenAttribute
Windows.Foundation.Metadata.ContractVersionAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.MarshalingBehaviorAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ActivatableAttribute
Windows.Foundation.Metadata.StaticAttribute
Windows.Foundation.Metadata.ActivatableAttribute
Windows.Foundation.Metadata.ThreadingAttribute

Details

Assembly

Windows.UI.Xaml.Controls.dll