WebView WebView WebView WebView Class

Definition

Provides a control that hosts HTML content in an app.

public : sealed class WebView : FrameworkElement, IWebView, IWebView2, IWebView3, IWebView4, IWebView5public sealed class WebView : FrameworkElement, IWebView, IWebView2, IWebView3, IWebView4, IWebView5Public NotInheritable Class WebView Inherits FrameworkElement Implements IWebView, IWebView2, IWebView3, IWebView4, IWebView5// This API is not available in Javascript.
<WebView .../>
        
Inheritance
Attributes
Windows 10 requirements
Device family
Windows 10 (introduced v10.0.10240.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v1)

Inherited Members

Inherited properties

Inherited events

Inherited methods

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

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 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 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 WebView.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 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 method. This method supports only HttpMethod.Post and HttpMethod.Get for the HttpRequestMessage.Method property value.

To load uncompressed and unencrypted content from your app’s LocalFolder or TemporaryFolder data stores, use the Navigate 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 NavigateToLocalStreamUri.)

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 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 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:

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;
}
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();
    }
}
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";
    }
}
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 WebViewPermissionRequest.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 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 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 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.

Accessing the Windows Runtime in WebView

Starting in Windows 10, you can use the AddWebAllowedObject 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 AllowForWeb 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 WebView.AddWebAllowedObject.

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 WebView.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 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 WebView.DefaultExecutionMode static property to query the default threading behavior for the current client. If necessary, you can use the WebView(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.

Use of Alert

If a web page hosted in a WebView uses the JavaScript Alert function, it will not be displayed. This is by design for all versions of WebView.

You might be able to intercept the information displayed by an Alert and do what you want with it in the host application. Whether this is possible depends on how the page is written and whether you have control of it. A sample is available that demonstrates one possible technique to do this. The sample is written for Windows 8.1 and Windows Phone 8.1, but will also work for apps using the Universal Windows Platform (UWP). However, this might not work for every scenario.

How to intercept JavaScript alert in WebView in universal Windows apps sample

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 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.

Constructors

WebView() WebView() WebView() WebView()

Initializes a new instance of the WebView class.

public : WebView()public WebView()Public Sub New()// This API is not available in Javascript.
See Also

WebView(WebViewExecutionMode) WebView(WebViewExecutionMode) WebView(WebViewExecutionMode) WebView(WebViewExecutionMode)

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

public : WebView(WebViewExecutionMode executionMode)public WebView(WebViewExecutionMode executionMode)Public Sub New(executionMode As WebViewExecutionMode)// This API is not available in Javascript.
Parameters
executionMode
WebViewExecutionMode WebViewExecutionMode WebViewExecutionMode WebViewExecutionMode

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

See Also

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 IList<Uri> AllowedScriptNotifyUris { get; set; }Public ReadWrite Property AllowedScriptNotifyUris As IList<Uri>// This API is not available in Javascript.
Value
IVector<Uri> IList<Uri> IList<Uri> IList<Uri>

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.

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 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// This API is not available in Javascript.

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.

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 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 IList<Uri> AnyScriptNotifyUri { get; }Public Static ReadOnly Property AnyScriptNotifyUri As IList<Uri>// This API is not available in Javascript.
Value
IVector<Uri> IList<Uri> IList<Uri> IList<Uri>

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.

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 method.

CanGoBack CanGoBack CanGoBack CanGoBack

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

public : PlatForm::Boolean CanGoBack { get; }public bool CanGoBack { get; }Public ReadOnly Property CanGoBack As bool// This API is not available in Javascript.
Value
PlatForm::Boolean bool bool bool

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

Remarks

To navigate backward, call the GoBack method.

See Also

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the CanGoBack dependency property.

CanGoForward CanGoForward CanGoForward CanGoForward

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

public : PlatForm::Boolean CanGoForward { get; }public bool CanGoForward { get; }Public ReadOnly Property CanGoForward As bool// This API is not available in Javascript.
Value
PlatForm::Boolean bool bool bool

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

Remarks

To navigate forward, call the GoForward method.

See Also

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the CanGoForward dependency property.

ContainsFullScreenElement ContainsFullScreenElement ContainsFullScreenElement ContainsFullScreenElement

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

public : PlatForm::Boolean ContainsFullScreenElement { get; }public bool ContainsFullScreenElement { get; }Public ReadOnly Property ContainsFullScreenElement As bool// This API is not available in Javascript.
Value
PlatForm::Boolean 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// This API is not available in Javascript.

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// This API is not available in Javascript.
Value
DataPackage DataPackage DataPackage DataPackage

A clipboard data package.

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

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.

See Also

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// This API is not available in Javascript.

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// This API is not available in Javascript.
<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"/>
Value
Color Color Color Color

The background color.

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// This API is not available in Javascript.
See Also

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// This API is not available in Javascript.
Value
WebViewExecutionMode WebViewExecutionMode WebViewExecutionMode WebViewExecutionMode

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

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 IList<WebViewDeferredPermissionRequest> DeferredPermissionRequests { get; }Public ReadOnly Property DeferredPermissionRequests As IList<WebViewDeferredPermissionRequest>// This API is not available in Javascript.
Value
IVector<WebViewDeferredPermissionRequest> IList<WebViewDeferredPermissionRequest> IList<WebViewDeferredPermissionRequest> IList<WebViewDeferredPermissionRequest>

A collection of WebViewDeferredPermissionRequest objects that are waiting to be granted or denied.

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 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.

See Also

DocumentTitle DocumentTitle DocumentTitle DocumentTitle

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

public : PlatForm::String DocumentTitle { get; }public string DocumentTitle { get; }Public ReadOnly Property DocumentTitle As string// This API is not available in Javascript.
Value
PlatForm::String 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// This API is not available in Javascript.
See Also

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// This API is not available in Javascript.
Value
WebViewExecutionMode WebViewExecutionMode WebViewExecutionMode WebViewExecutionMode

A value of the enumeration that specifies whether the WebView hosts content on the UI thread or a non-UI thread.

Remarks

To create a WebView with a specific ExecutionMode, use the WebView(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 FlipView.)
  • Tab navigation to escape focus on WebView.
  • Printing.
See Also

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// This API is not available in Javascript.
Value
WebViewSettings WebViewSettings WebViewSettings WebViewSettings

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

Remarks

Use the WebViewSettings object to enable or disable the use of JavaScript and IndexedDB in the WebView. See WebViewSettings.IsIndexedDBEnabled and WebViewSettings.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// This API is not available in Javascript.
<WebView Source="uriString"/>
Value
Uri Uri Uri Uri

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the Source dependency property.

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// This API is not available in Javascript.
<WebView XYFocusDown="{x:Bind dependencyObjectValue}"/>
Value
DependencyObject DependencyObject DependencyObject DependencyObject

The object that gets focus when a user presses the Directional Pad (D-pad).

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the XYFocusDown dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
<WebView XYFocusLeft="{x:Bind dependencyObjectValue}"/>
Value
DependencyObject DependencyObject DependencyObject DependencyObject

The object that gets focus when a user presses the Directional Pad (D-pad).

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the XYFocusLeft dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
<WebView XYFocusRight="{x:Bind dependencyObjectValue}"/>
Value
DependencyObject DependencyObject DependencyObject DependencyObject

The object that gets focus when a user presses the Directional Pad (D-pad).

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the XYFocusRight dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
<WebView XYFocusUp="{x:Bind dependencyObjectValue}"/>
Value
DependencyObject DependencyObject DependencyObject DependencyObject

The object that gets focus when a user presses the Directional Pad (D-pad).

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

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// This API is not available in Javascript.
Value
DependencyProperty DependencyProperty DependencyProperty DependencyProperty

The identifier for the XYFocusUp dependency property.

Additional features and requirements
Device family
Windows 10 Anniversary Edition (introduced v10.0.14393.0)
API contract
Windows.Foundation.UniversalApiContract (introduced v3)

Methods

AddWebAllowedObject(String, Object) AddWebAllowedObject(String, Object) AddWebAllowedObject(String, Object) AddWebAllowedObject(String, Object)

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

public : void AddWebAllowedObject(PlatForm::String name, PlatForm::Object pObject)public void AddWebAllowedObject(String name, Object pObject)Public Function AddWebAllowedObject(name As String, pObject As Object) As void// This API is not available in Javascript.
Parameters
name
PlatForm::String String String String

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

pObject
PlatForm::Object Object Object Object

The object to expose to the document in the WebView.

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>

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 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 does not work.

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

BuildLocalStreamUri(String, String) BuildLocalStreamUri(String, String) BuildLocalStreamUri(String, String) BuildLocalStreamUri(String, String)

Creates a URI that you can pass to NavigateToLocalStreamUri.

public : Uri BuildLocalStreamUri(PlatForm::String contentIdentifier, PlatForm::String relativePath)public Uri BuildLocalStreamUri(String contentIdentifier, String relativePath)Public Function BuildLocalStreamUri(contentIdentifier As String, relativePath As String) As Uri// This API is not available in Javascript.
Parameters
contentIdentifier
PlatForm::String String String String

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

relativePath
PlatForm::String String String String

The path to the resource, relative to the root.

Returns
Uri Uri Uri Uri

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

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"); }
    }
}
See Also

CapturePreviewToStreamAsync(IRandomAccessStream) CapturePreviewToStreamAsync(IRandomAccessStream) CapturePreviewToStreamAsync(IRandomAccessStream) CapturePreviewToStreamAsync(IRandomAccessStream)

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

public : IAsyncAction CapturePreviewToStreamAsync(IRandomAccessStream stream)public IAsyncAction CapturePreviewToStreamAsync(IRandomAccessStream stream)Public Function CapturePreviewToStreamAsync(stream As IRandomAccessStream) As IAsyncAction// This API is not available in Javascript.
Parameters
Returns

An asynchronous action to await the capture operation.

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);
}
See Also

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 )// This API is not available in Javascript.
Returns

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 DataRequestedEventArgs.Request.GetDeferral to create the deferral and DataRequestDeferral.Complete to end it.

See Also

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// This API is not available in Javascript.
Returns

An asynchronous action to await the clear operation.

DeferredPermissionRequestById(UInt32) DeferredPermissionRequestById(UInt32) DeferredPermissionRequestById(UInt32) DeferredPermissionRequestById(UInt32)

Returns the deferred permission request with the specified Id.

public : WebViewDeferredPermissionRequest DeferredPermissionRequestById(unsigned int id)public WebViewDeferredPermissionRequest DeferredPermissionRequestById(UInt32 id)Public Function DeferredPermissionRequestById(id As UInt32) As WebViewDeferredPermissionRequest// This API is not available in Javascript.
Parameters
id
unsigned int UInt32 UInt32 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 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.

See Also

Focus(FocusState) Focus(FocusState) Focus(FocusState) Focus(FocusState)

Sets the input focus to the WebView.

public : PlatForm::Boolean Focus(FocusState value)public bool Focus(FocusState value)Public Function Focus(value As FocusState) As bool// This API is not available in Javascript.
Parameters
value
FocusState FocusState FocusState FocusState

A value that indicates how the focus was set.

Returns
PlatForm::Boolean 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 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// This API is not available in Javascript.

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// This API is not available in Javascript.

InvokeScript(String, String[]) InvokeScript(String, String[]) InvokeScript(String, String[]) InvokeScript(String, String[])

Note

InvokeScript may be altered or unavailable for releases after Windows 8.1. Instead, use InvokeScriptAsync.

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

public : PlatForm::String InvokeScript(PlatForm::String scriptName, PlatForm::String[] arguments)public string InvokeScript(String scriptName, String[] arguments)Public Function InvokeScript(scriptName As String, arguments As String[]) As string// This API is not available in Javascript.
Parameters
scriptName
PlatForm::String String String String

The name of the script function to invoke.

arguments
PlatForm::String[] String[] String[] String[]

A string array that packages arguments to the script function.

Returns
PlatForm::String string string string

The result of the script invocation.

Remarks

The invoked script can return only string values.

See Also

InvokeScriptAsync(String, IIterable) InvokeScriptAsync(String, IIterable) InvokeScriptAsync(String, IIterable) InvokeScriptAsync(String, IIterable)

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

public : IAsyncOperation<PlatForm::String> InvokeScriptAsync(PlatForm::String scriptName, IIterable<PlatForm::String> arguments)public IAsyncOperation<string> InvokeScriptAsync(String scriptName, IEnumerable<String> arguments)Public Function InvokeScriptAsync(scriptName As String, arguments As IEnumerable<String>) As IAsyncOperation( Of string )// This API is not available in Javascript.
Parameters
scriptName
PlatForm::String String String String

The name of the script function to invoke.

arguments
IIterable<PlatForm::String> IEnumerable<String> IEnumerable<String> IEnumerable<String>

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(Uri) Navigate(Uri) Navigate(Uri) Navigate(Uri)

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

public : void Navigate(Uri source)public void Navigate(Uri source)Public Function Navigate(source As Uri) As void// This API is not available in Javascript.
Parameters
source
Uri Uri Uri Uri

The Uniform Resource Identifier (URI) to load.

See Also

NavigateToLocalStreamUri(Uri, IUriToStreamResolver) NavigateToLocalStreamUri(Uri, IUriToStreamResolver) NavigateToLocalStreamUri(Uri, IUriToStreamResolver) NavigateToLocalStreamUri(Uri, IUriToStreamResolver)

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

public : void NavigateToLocalStreamUri(Uri source, IUriToStreamResolver streamResolver)public void NavigateToLocalStreamUri(Uri source, IUriToStreamResolver streamResolver)Public Function NavigateToLocalStreamUri(source As Uri, streamResolver As IUriToStreamResolver) As void// This API is not available in Javascript.
Parameters
source
Uri Uri Uri Uri

A URI identifying the local HTML content to load.

streamResolver
IUriToStreamResolver IUriToStreamResolver IUriToStreamResolver IUriToStreamResolver

A resolver that converts the URI into a stream to load.

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

Remarks

Use this method to load local content that the NavigateToString method won't handle. NavigateToString 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 does not provide a way to generate these resources programmatically.

To use the NavigateToLocalStreamUri 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 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 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

See Also

NavigateToString(String) NavigateToString(String) NavigateToString(String) NavigateToString(String)

Loads the specified HTML content as a new document.

public : void NavigateToString(PlatForm::String text)public void NavigateToString(String text)Public Function NavigateToString(text As String) As void// This API is not available in Javascript.
Parameters
text
PlatForm::String String String String

The HTML content to display in the WebView control.

Remarks

NavigateToString 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 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 to provide this support.

See Also

NavigateWithHttpRequestMessage(HttpRequestMessage) NavigateWithHttpRequestMessage(HttpRequestMessage) NavigateWithHttpRequestMessage(HttpRequestMessage) NavigateWithHttpRequestMessage(HttpRequestMessage)

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

public : void NavigateWithHttpRequestMessage(HttpRequestMessage requestMessage)public void NavigateWithHttpRequestMessage(HttpRequestMessage requestMessage)Public Function NavigateWithHttpRequestMessage(requestMessage As HttpRequestMessage) As void// This API is not available in Javascript.
Parameters
requestMessage
HttpRequestMessage HttpRequestMessage HttpRequestMessage HttpRequestMessage

The details of the HTTP request.

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

Remarks

This method supports only HttpMethod.Post and HttpMethod.Get for the HttpRequestMessage.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.

Refresh() Refresh() Refresh() Refresh()

Reloads the current content in the WebView.

public : void Refresh()public void Refresh()Public Function Refresh() As void// This API is not available in Javascript.

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// This API is not available in Javascript.

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 ContainsFullScreenElementChanged<WebView,  object>public event TypedEventHandler ContainsFullScreenElementChanged<WebView,  object>Public Event ContainsFullScreenElementChanged<WebView,  object>// This API is not available in Javascript.
<WebView ContainsFullScreenElementChanged="eventhandler"/>

ContentLoading ContentLoading ContentLoading ContentLoading

Occurs when the WebView has started loading new content.

public : event TypedEventHandler ContentLoading<WebView,  WebViewContentLoadingEventArgs>public event TypedEventHandler ContentLoading<WebView,  WebViewContentLoadingEventArgs>Public Event ContentLoading<WebView,  WebViewContentLoadingEventArgs>// This API is not available in Javascript.
<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 DOMContentLoaded<WebView,  WebViewDOMContentLoadedEventArgs>public event TypedEventHandler DOMContentLoaded<WebView,  WebViewDOMContentLoadedEventArgs>Public Event DOMContentLoaded<WebView,  WebViewDOMContentLoadedEventArgs>// This API is not available in Javascript.
<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 FrameContentLoading<WebView,  WebViewContentLoadingEventArgs>public event TypedEventHandler FrameContentLoading<WebView,  WebViewContentLoadingEventArgs>Public Event FrameContentLoading<WebView,  WebViewContentLoadingEventArgs>// This API is not available in Javascript.
<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 FrameDOMContentLoaded<WebView,  WebViewDOMContentLoadedEventArgs>public event TypedEventHandler FrameDOMContentLoaded<WebView,  WebViewDOMContentLoadedEventArgs>Public Event FrameDOMContentLoaded<WebView,  WebViewDOMContentLoadedEventArgs>// This API is not available in Javascript.
<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 FrameNavigationCompleted<WebView,  WebViewNavigationCompletedEventArgs>public event TypedEventHandler FrameNavigationCompleted<WebView,  WebViewNavigationCompletedEventArgs>Public Event FrameNavigationCompleted<WebView,  WebViewNavigationCompletedEventArgs>// This API is not available in Javascript.
<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 FrameNavigationStarting<WebView,  WebViewNavigationStartingEventArgs>public event TypedEventHandler FrameNavigationStarting<WebView,  WebViewNavigationStartingEventArgs>Public Event FrameNavigationStarting<WebView,  WebViewNavigationStartingEventArgs>// This API is not available in Javascript.
<WebView FrameNavigationStarting="eventhandler"/>

Remarks

You can cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.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// This API is not available in Javascript.
<WebView LoadCompleted="eventhandler"/>

LongRunningScriptDetected LongRunningScriptDetected LongRunningScriptDetected LongRunningScriptDetected

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

public : event TypedEventHandler LongRunningScriptDetected<WebView,  WebViewLongRunningScriptDetectedEventArgs>public event TypedEventHandler LongRunningScriptDetected<WebView,  WebViewLongRunningScriptDetectedEventArgs>Public Event LongRunningScriptDetected<WebView,  WebViewLongRunningScriptDetectedEventArgs>// This API is not available in Javascript.
<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 NavigationCompleted<WebView,  WebViewNavigationCompletedEventArgs>public event TypedEventHandler NavigationCompleted<WebView,  WebViewNavigationCompletedEventArgs>Public Event NavigationCompleted<WebView,  WebViewNavigationCompletedEventArgs>// This API is not available in Javascript.
<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// This API is not available in Javascript.
<WebView NavigationFailed="eventhandler" />

NavigationStarting NavigationStarting NavigationStarting NavigationStarting

Occurs before the WebView navigates to new content.

public : event TypedEventHandler NavigationStarting<WebView,  WebViewNavigationStartingEventArgs>public event TypedEventHandler NavigationStarting<WebView,  WebViewNavigationStartingEventArgs>Public Event NavigationStarting<WebView,  WebViewNavigationStartingEventArgs>// This API is not available in Javascript.
<WebView NavigationStarting="eventhandler" />

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}\".
", url)); pageIsLoading = true; } }

Remarks

You can cancel navigation in a handler for this event by setting the WebViewNavigationStartingEventArgs.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:

See Also

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 NewWindowRequested<WebView,  WebViewNewWindowRequestedEventArgs>public event TypedEventHandler NewWindowRequested<WebView,  WebViewNewWindowRequestedEventArgs>Public Event NewWindowRequested<WebView,  WebViewNewWindowRequestedEventArgs>// This API is not available in Javascript.
<WebView NewWindowRequested="eventhandler"/>

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

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.

PermissionRequested PermissionRequested PermissionRequested PermissionRequested

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

public : event TypedEventHandler PermissionRequested<WebView,  WebViewPermissionRequestedEventArgs>public event TypedEventHandler PermissionRequested<WebView,  WebViewPermissionRequestedEventArgs>Public Event PermissionRequested<WebView,  WebViewPermissionRequestedEventArgs>// This API is not available in Javascript.

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 WebViewPermissionRequestedEventArgs.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 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// This API is not available in Javascript.
<WebView ScriptNotify="eventhandler"/>

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.
}

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.

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 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, 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.

See Also

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 UnsafeContentWarningDisplaying<WebView,  object>public event TypedEventHandler UnsafeContentWarningDisplaying<WebView,  object>Public Event UnsafeContentWarningDisplaying<WebView,  object>// This API is not available in Javascript.
<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 UnsupportedUriSchemeIdentified<WebView,  WebViewUnsupportedUriSchemeIdentifiedEventArgs>public event TypedEventHandler UnsupportedUriSchemeIdentified<WebView,  WebViewUnsupportedUriSchemeIdentifiedEventArgs>Public Event UnsupportedUriSchemeIdentified<WebView,  WebViewUnsupportedUriSchemeIdentifiedEventArgs>// This API is not available in Javascript.
<WebView UnsupportedUriSchemeIdentified="eventhandler"/>

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

Remarks

See WebViewUnsupportedUriSchemeIdentifiedEventArgs.

WebView supports navigation to Uniform Resource Identifier (URI) using these schemes: http, https, ms-appx-web, ms-appdata 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.

UnviewableContentIdentified UnviewableContentIdentified UnviewableContentIdentified UnviewableContentIdentified

Occurs when the WebView attempts to download an unsupported file.

public : event TypedEventHandler UnviewableContentIdentified<WebView,  WebViewUnviewableContentIdentifiedEventArgs>public event TypedEventHandler UnviewableContentIdentified<WebView,  WebViewUnviewableContentIdentifiedEventArgs>Public Event UnviewableContentIdentified<WebView,  WebViewUnviewableContentIdentifiedEventArgs>// This API is not available in Javascript.
<WebView UnviewableContentIdentified="eventhandler" />

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.
", 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; }

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.

See Also

See Also