Class CoreWebView2
WebView2 enables you to host web content using the latest Microsoft Edge browser and web technology.
public class CoreWebView2
- Inheritance
-
CoreWebView2
- Inherited Members
Properties
BrowserProcessId
Gets the process ID of the browser process that hosts the WebView.
public uint BrowserProcessId { get; }
Property Value
CanGoBack
true
if the WebView is able to navigate to a previous page in the navigation history.
public bool CanGoBack { get; }
Property Value
Remarks
If CanGoBack changes value, the HistoryChanged event is raised.
- See Also
CanGoForward
true
if the WebView is able to navigate to a next page in the navigation history.
public bool CanGoForward { get; }
Property Value
Remarks
If CanGoForward changes value, the HistoryChanged event is raised.
- See Also
ContainsFullScreenElement
Indicates if the WebView contains a fullscreen HTML element.
public bool ContainsFullScreenElement { get; }
Property Value
CookieManager
Gets the CoreWebView2CookieManager object associated with this CoreWebView2.
public CoreWebView2CookieManager CookieManager { get; }
Property Value
- See Also
DefaultDownloadDialogCornerAlignment
The default download dialog corner alignment.
public CoreWebView2DefaultDownloadDialogCornerAlignment DefaultDownloadDialogCornerAlignment { get; set; }
Property Value
Examples
Remarks
The dialog can be aligned to any of the WebView corners (see CoreWebView2DefaultDownloadDialogCornerAlignment). When the WebView or dialog changes size, the dialog keeps it position relative to the corner. The dialog may become partially or completely outside of the WebView bounds if the WebView is small enough. Set the margin from the corner with the DefaultDownloadDialogMargin property. The corner alignment and margin should be set during initialization to ensure that they are correctly applied when the layout is first computed, otherwise they will not take effect until the next time the WebView position or size is updated.
DefaultDownloadDialogMargin
The default download dialog margin relative to the WebView corner specified by DefaultDownloadDialogCornerAlignment.
public Point DefaultDownloadDialogMargin { get; set; }
Property Value
Remarks
The margin is a point that describes the vertical and horizontal distances between the chosen WebView corner and the default download dialog corner nearest to it. Positive values move the dialog towards the center of the WebView from the chosen WebView corner, and negative values move the dialog away from it. Use (0, 0) to align the dialog to the WebView corner with no margin. The corner alignment and margin should be set during initialization to ensure that they are correctly applied when the layout is first computed, otherwise they will not take effect until the next time the WebView position or size is updated.
DocumentTitle
Gets the title for the current top-level document.
public string DocumentTitle { get; }
Property Value
Examples
Remarks
If the document has no explicit title or is otherwise empty, a default that may or may not match the URI of the document is used.
Environment
Exposes the CoreWebView2Environment used to create this CoreWebView2.
public CoreWebView2Environment Environment { get; }
Property Value
FaviconUri
Get the Uri as a string of the current Favicon. This will be an empty string if the page does not have a Favicon.
public string FaviconUri { get; }
Property Value
FrameId
public uint FrameId { get; }
Property Value
Remarks
FrameId may not be valid if CoreWebView2 has not done any navigation. It's safe to get this value during or after the first ContentLoading event. Otherwise, it could return the invalid frame Id 0
.
IsDefaultDownloadDialogOpen
True if the default download dialog is currently open.
public bool IsDefaultDownloadDialogOpen { get; }
Property Value
Examples
Remarks
The value of this property changes only when the default download dialog is explicitly opened or closed. Hiding the WebView implicitly hides the dialog, but does not change the value of this property.
IsDocumentPlayingAudio
Indicates whether any audio output from this CoreWebView2 is playing. true
if audio is playing even if IsMuted is true.
public bool IsDocumentPlayingAudio { get; }
Property Value
Examples
IsMuted
Indicates whether all audio output from this CoreWebView2 is muted or not. Set to true will mute this CoreWebView2, and set to false will unmute this CoreWebView2. true
if audio is muted.
public bool IsMuted { get; set; }
Property Value
Examples
IsSuspended
Whether WebView is suspended.
public bool IsSuspended { get; }
Property Value
Remarks
True when WebView is suspended, from the time when TrySuspendAsync() has completed successfully until WebView is resumed.
MemoryUsageTargetLevel
Desired CoreWebView2MemoryUsageTargetLevel of a WebView.
public CoreWebView2MemoryUsageTargetLevel MemoryUsageTargetLevel { get; set; }
Property Value
Remarks
An app may set MemoryUsageTargetLevel to indicate desired memory consumption level of WebView. Scripts will not be impacted and continue to run. This is useful for inactive apps that still want to run scripts and/or keep network connections alive and therefore could not call TrySuspendAsync() and Resume() to reduce memory consumption. These apps can set memory usage target level to Low when the app becomes inactive, and set back to Normal when the app becomes active.
It is not necessary to set CoreWebView2Controller's IsVisible property to false when setting the property.
It is a best effort operation to change memory usage level, and the API will return before the operation completes.
Setting the level to Low could potentially cause memory for some WebView browser processes to be swapped out to disk in some circumstances. It is a best effort to reduce memory usage as much as possible. If a script runs after its related memory has been swapped out, the memory will be swapped back in to ensure the script can still run, but performance might be impacted. Therefore, the app should set the level back to Normal when the app becomes active again. Setting memory usage target level back to normal will not happen automatically.
An app should choose to use either the combination of TrySuspendAsync() and Resume() or the combination of setting MemoryUsageTargetLevel to Low and Normal. It is not advisable to mix them. Trying to set MemoryUsageTargetLevel while suspended will be ignored. The TrySuspendAsync() and Resume() methods will change the MemoryUsageTargetLevel. TrySuspendAsync() will automatically set MemoryUsageTargetLevel to Low while Resume() on suspended WebView will automatically set MemoryUsageTargetLevel to Normal. Calling Resume() when the WebView is not suspended would not change MemoryUsageTargetLevel.
Profile
The associated CoreWebView2Profile object of CoreWebView2.
public CoreWebView2Profile Profile { get; }
Property Value
Examples
Settings
Gets the CoreWebView2Settings object contains various modifiable settings for the running WebView.
public CoreWebView2Settings Settings { get; }
Property Value
Source
Gets the URI of the current top level document.
public string Source { get; }
Property Value
Remarks
This value potentially changes as a part of the SourceChanged event raised for some cases such as navigating to a different site or fragment navigations. It remains the same for other types of navigations such as page refreshes or history.pushState
with the same URL as the current page.
- See Also
StatusBarText
The current text of the statusbar as defined by Window.statusbar.
public string StatusBarText { get; }
Property Value
Methods
AddHostObjectToScript(string, object)
Adds the provided host object to script running in the WebView with the specified name.
public void AddHostObjectToScript(string name, object rawObject)
Parameters
Examples
To create a IDispatch implementing class in C# use the following attributes on each class you intend to expose.
// Bridge and BridgeAnotherClass are C# classes that implement IDispatch and works with AddHostObjectToScript.
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class BridgeAnotherClass
{
// Sample property.
public string Prop { get; set; } = "Example";
}
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class Bridge
{
public string Func(string param)
{
return "Example: " + param;
}
public BridgeAnotherClass AnotherObject { get; set; } = new BridgeAnotherClass();
// Sample indexed property.
[System.Runtime.CompilerServices.IndexerName("Items")]
public string this[int index]
{
get { return m_dictionary[index]; }
set { m_dictionary[index] = value; }
}
private Dictionary<int, string> m_dictionary = new Dictionary<int, string>();
}
Then add instances of those classes via AddHostObjectToScript(string, object):
webView.CoreWebView2.AddHostObjectToScript("bridge", new Bridge());
And then in script you can call the methods, and access those properties of the objects added via AddHostObjectToScript(string, object).
Note that CoreWebView2.AddHostObjectToScript
only applies to the top-level document and not to frames. To add host objects to frames use CoreWebView2Frame.AddHostObjectToScript
.
// Find added objects on the hostObjects property
const bridge = chrome.webview.hostObjects.bridge;
// Call a method and pass in a parameter.
// The result is another proxy promise so you must await to get the result.
console.log(await bridge.Func("testing..."));
// A property may be another object as long as its class also implements
// IDispatch.
// Getting a property also gets a proxy promise you must await.
const propValue = await bridge.AnotherObject.Prop;
console.log(propValue);
// Indexed properties
let index = 123;
bridge[index] = "test";
let result = await bridge[index];
console.log(result);
Remarks
Host objects are exposed as host object proxies via window.chrome.webview.hostObjects.{name}
. Host object proxies are promises and will resolve to an object representing the host object. Only the COM visible objects/properties/methods can be accessed from script.
The app can control which part of .NET objects are exposed using ComVisibleAttribute.
JavaScript code in the WebView will be able to access appObject as following and then access attributes and methods of appObject.
Note that while simple types, IDispatch
and array are supported, and IUnknown
objects that also implement IDispatch
are treated as IDispatch
, generic IUnknown
, VT_DECIMAL
, or VT_RECORD
variant is not supported. Remote JavaScript objects like callback functions are represented as an VT_DISPATCH
VARIANT with the object implementing IDispatch
. The JavaScript callback method may be invoked using DISPID_VALUE for the DISPID. Such callback method invocations will return immediately and will not wait for the JavaScript function to run and so will not provide the return value of the JavaScript function. Nested arrays are supported up to a depth of 3. Arrays of by reference types are not supported. VT_EMPTY
and VT_NULL
are mapped into JavaScript as null
. In JavaScript null
and undefined
are mapped to VT_EMPTY
.
Additionally, all host objects are exposed as window.chrome.webview.hostObjects.sync.{name}
. Here the host objects are exposed as synchronous host object proxies. These are not promises and calls to functions or property access synchronously block running script waiting to communicate cross process for the host code to run. Accordingly this can result in reliability issues and it is recommended that you use the promise based asynchronous window.chrome.webview.hostObjects.{name}
API described above.
Synchronous host object proxies and asynchronous host object proxies can both proxy the same host object. Remote changes made by one proxy will be reflected in any other proxy of that same host object whether the other proxies and synchronous or asynchronous.
While JavaScript is blocked on a synchronous call to native code, that native code is unable to call back to JavaScript. Attempts to do so will fail with HRESULT_FROM_WIN32(ERROR_POSSIBLE_DEADLOCK)
.
Host object proxies are JavaScript Proxy objects that intercept all property get, property set, and method invocations. Properties or methods that are a part of the Function or Object prototype are run locally. Additionally any property or method in the array chrome.webview.hostObjects.options.forceLocalProperties
will also be run locally. This defaults to including optional methods that have meaning in JavaScript like toJSON
and Symbol.toPrimitive
. You can add more to this array as required.
There's a method chrome.webview.hostObjects.cleanupSome
that will best effort garbage collect host object proxies.
The chrome.webview.hostObjects.options
object provides the ability to change some functionality of host objects.
Options property | Details |
---|---|
forceLocalProperties |
This is an array of host object property names that will be run locally, instead of being called on the native host object. This defaults to then , toJSON , Symbol.toString , and Symbol.toPrimitive . You can add other properties to specify that they should be run locally on the JavaScript host object proxy.
|
log |
This is a callback that will be called with debug information. For example, you can set this to console.log.bind(console) to have it print debug information to the console to help when troubleshooting host object usage. By default this is null.
|
shouldSerializeDates |
By default this is false, and JavaScript Date objects will be sent to host objects as a string using JSON.stringify . You can set this property to true to have Date objects properly serialize as a System.DateTime when sending to the .NET host object, and have System.DateTime properties and return values create a JavaScript Date object.
|
defaultSyncProxy | When calling a method on a synchronous proxy, the result should also be a synchronous proxy. But in some cases, the sync/async context is lost (for example, when providing to native code a reference to a function, and then calling that function in native code). In these cases, the proxy will be asynchronous, unless this property is set. |
forceAsyncMethodMatches |
This is an array of regular expressions. When calling a method on a synchronous proxy, the method call will be performed asynchronously if the method name matches a string or regular expression in this array. Setting this value to Async will make any method that ends with Async be an asynchronous method call. If an async method doesn't match here and isn't forced to be asynchronous, the method will be invoked synchronously, blocking execution of the calling JavaScript and then returning the resolution of the promise, rather than returning a promise.
|
ignoreMemberNotFoundError |
By default, an exception is thrown when attempting to get the value of a proxy property that doesn't exist on the corresponding native class. Setting this property to true switches the behavior to match Chakra WinRT projection (and general JavaScript) behavior of returning undefined with no error.
|
shouldPassTypedArraysAsArrays | By default, typed arrays will be passed to host as IDispatch. Otherwise, set to true to pass typed arrays to host as array. |
Host object proxies additionally have the following methods:
Method name | Details |
---|---|
applyHostFunction , getHostProperty , setHostProperty |
Perform a method invocation, property get, or property set on the host object. You can use these to explicitly force a method or property to run remotely if there is a conflicting local method or property. For instance, proxy.toString() will run the local toString method on the proxy object. But proxy.applyHostFunction('toString') runs toString on the host proxied object instead.
|
getLocalProperty , setLocalProperty |
Perform property get, or property set locally. You can use these methods to force getting or setting a property on the host object proxy itself rather than on the host object it represents. For instance, proxy.unknownProperty will get the property named unknownProperty from the host proxied object. But proxy.getLocalProperty('unknownProperty') will get the value of the property unknownProperty on the proxy object itself.
|
addEventListener |
This method only exists on proxies for .NET objects. Bind the JavaScript handler to the C# event, so that the JavaScript handler can be called through the C# event. For example, chrome.webview.hostObjects.sample.addEventListener('TestEvent', () => { alert('Invoked from remote');}); bind an anonymous JavaScript function to a C# event called 'TestEvent'. When calling TestEvent?.Invoke() on C# side, the JavaScript function that was just bound will be called asynchronously. It allows adding more than one handler for an event, but if the handler is already in the list of event handler, it will not be added a second time. If the host object cannot find the event with the name passed in by the addEventListener function or it is no public or its return type is not void, an exception will be thrown. If the count and type of C# event's parameters do not match the count and type of JavaScript handler, invoke addEventListener will be successful but an exception will be passed to JavaScript when invoke the event on C# side. If the host object has defined addEventListener function, use the defined function rather than the additionally addEventListener function.
|
removeEventListener |
This method only exists on proxies for .NET objects. Removes a handler previously bound with addEventListener() . If the handler does not exist in the list of event handler, nothing will happen. If the host object cannot find the event with the name passed in by the removeEventListener function or it is no public, an exception will be thrown. If the host object has defined removeEventListener function, use the defined function rather than the additionally removeEventListener function.
|
sync |
Asynchronous host object proxies expose a sync method which returns a promise for a synchronous host object proxy for the same host object. For example, chrome.webview.hostObjects.sample.methodCall() returns an asynchronous host object proxy. You can use the sync method to obtain a synchronous host object proxy instead:
const syncProxy = await chrome.webview.hostObjects.sample.methodCall().sync()
|
async |
Synchronous host object proxies expose an async method which blocks and returns an asynchronous host object proxy for the same host object. For example, chrome.webview.hostObjects.sync.sample.methodCall() returns a synchronous host object proxy. Calling the async method on this blocks and then returns an asynchronous host object proxy for the same host object: const asyncProxy = chrome.webview.hostObjects.sync.sample.methodCall().async()
|
then |
Asynchronous host object proxies have a then method. This allows them to be awaitable. then will return a promise that resolves with a representation of the host object. If the proxy represents a JavaScript literal then a copy of that is returned locally. If the proxy represents a function then a non-awaitable proxy is returned. If the proxy represents a JavaScript object with a mix of literal properties and function properties, then the a copy of the object is returned with some properties as host object proxies.
|
cancelPromise |
This method attempts to cancel the fulfillment of a promised value. If the promise hasn't already been fulfilled and cancelation is supported, the promise will get rejected. cancelPromise supports cancelation of IAsyncOperation and IAsyncAction methods. If the promise is successfully canceled, then calling await on the promise will throw. For example, chrome.webview.hostObjects.cancelPromise(promise); await promise; will throw with "Promise Canceled". Once a promise has been canceled, a subsequent cancel on the same promise will throw an exception as well.
|
All other property and method invocations (other than the above Remote object proxy methods, forceLocalProperties
list, and properties on Function and Object prototypes) are run remotely. Asynchronous host object proxies return a promise representing asynchronous completion of remotely invoking the method, or getting the property. The promise resolves after the remote operations complete and the promises resolve to the resulting value of the operation. Synchronous host object proxies work similarly but block JavaScript execution and wait for the remote operation to complete.
Setting a property on an asynchronous host object proxy works slightly differently. The set returns immediately and the return value is the value that will be set. This is a requirement of the JavaScript Proxy object. If you need to asynchronously wait for the property set to complete, use the setHostProperty
method which returns a promise as described above. Synchronous object property set property synchronously blocks until the property is set.
Exposing host objects to script has security risk. Please follow best practices.
- See Also
AddScriptToExecuteOnDocumentCreatedAsync(string)
Adds the provided JavaScript to a list of scripts that should be run after the global object has been created, but before the HTML document has been parsed and before any other script included by the HTML document is run.
public Task<string> AddScriptToExecuteOnDocumentCreatedAsync(string javaScript)
Parameters
javaScript
stringThe JavaScript code to be run.
Returns
- Task<string>
A script ID that may be passed when calling RemoveScriptToExecuteOnDocumentCreated(string).
Remarks
The injected script will apply to all future top level document and child frame navigations until removed with RemoveScriptToExecuteOnDocumentCreated(string). This is applied asynchronously and you must wait for the returned Task<TResult> to complete before you can be sure that the script is ready to execute on future navigations. If the method is run in NewWindowRequested handler, it should be called before the new window is set. For more details see NewWindow.
Note that if an HTML document has sandboxing of some kind via sandbox properties or the Content-Security-Policy HTTP header this will affect the script run here. So, for example, if the allow-modals
keyword is not set then calls to the alert
function will be ignored.
- See Also
AddWebResourceRequestedFilter(string, CoreWebView2WebResourceContext)
Adds a URI and resource context filter for the WebResourceRequested event.
public void AddWebResourceRequestedFilter(string uri, CoreWebView2WebResourceContext ResourceContext)
Parameters
uri
stringAn URI to be added to the WebResourceRequested event.
ResourceContext
CoreWebView2WebResourceContextA resource context filter to be added to the WebResourceRequested event.
Remarks
A web resource request with a resource context that matches this filter's resource context and a URI that matches this filter's URI wildcard string will be raised via the WebResourceRequested event.
The uri
parameter value is a wildcard string matched against the URI of the web resource request. This is a glob style wildcard string in which a matches zero or more characters and a
?
matches exactly one character.
These wildcard characters can be escaped using a backslash just before the wildcard character in order to represent the literal or
?
.
The matching occurs over the URI as a whole string and not limiting wildcard matches to particular parts of the URI. The wildcard filter is compared to the URI after the URI has been normalized, any URI fragment has been removed, and non-ASCII hostnames have been converted to punycode.
Specifying a nullptr
for the uri is equivalent to an empty string which matches no URIs.
For more information about resource context filters, navigate to CoreWebView2WebResourceContext.
URI Filter String | Request URI | Match | Notes |
---|---|---|---|
* | https://contoso.com/a/b/c | Yes | A single * will match all URIs |
*://contoso.com/* | https://contoso.com/a/b/c | Yes | Matches everything in contoso.com across all schemes |
*://contoso.com/* | https://example.com/?https://contoso.com/ | Yes | But also matches a URI with just the same text anywhere in the URI |
example | https://contoso.com/example | No | The filter does not perform partial matches |
*example | https://contoso.com/example | Yes | The filter matches across URI parts |
*example | https://contoso.com/path/?example | Yes | The filter matches across URI parts |
*example | https://contoso.com/path/?query#example | No | The filter is matched against the URI with no fragment |
*example | https://example | No | The URI is normalized before filter matching so the actual URI used for comparison is https://example.com/ |
*example/ | https://example | Yes | Just like above, but this time the filter ends with a / just like the normalized URI |
https://xn--qei.example/ | https://❤.example/ | Yes | Non-ASCII hostnames are normalized to punycode before wildcard comparison |
https://❤.example/ | https://xn--qei.example/ | No | Non-ASCII hostnames are normalized to punycode before wildcard comparison |
- See Also
AddWebResourceRequestedFilter(string, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds)
Adds a URI and resource context filter for corresponding request sources for the WebResourceRequested event.
public void AddWebResourceRequestedFilter(string uri, CoreWebView2WebResourceContext ResourceContext, CoreWebView2WebResourceRequestSourceKinds RequestSourceKinds)
Parameters
uri
stringA URI to be added to the WebResourceRequested event.
ResourceContext
CoreWebView2WebResourceContextA resource context filter to be added to the WebResourceRequested event.
RequestSourceKinds
CoreWebView2WebResourceRequestSourceKindsA request source filter to be added to the WebResourceRequested event.
CallDevToolsProtocolMethodAsync(string, string)
Runs an asynchronous DevToolsProtocol method.
public Task<string> CallDevToolsProtocolMethodAsync(string methodName, string parametersAsJson)
Parameters
methodName
stringThe full name of the method in the format
{domain}.{method}
.parametersAsJson
stringA JSON formatted string containing the parameters for the corresponding method.
Returns
Remarks
For more information about available methods, navigate to DevTools Protocol Viewer. The returned task is completed when the method asynchronously completes and will return the method's return object as a JSON string. Note even though WebView2 dispatches the CDP messages in the order called, CDP method calls may be processed out of order. If you require CDP methods to run in a particular order, you should await for the previous method call.
If the method is to run in NewWindowRequested handler it should be called before the new window is set if the cdp messages should affect the initial navigation. If called after setting the NewWindow property, the cdp messages may or may not apply to the initial navigation and may only apply to the subsequent navigation. For more details NewWindow.
CallDevToolsProtocolMethodForSessionAsync(string, string, string)
Runs an asynchronous DevToolsProtocol
method for a specific session of an attached target.
public Task<string> CallDevToolsProtocolMethodForSessionAsync(string sessionId, string methodName, string parametersAsJson)
Parameters
sessionId
stringThe sessionId for an attached target. null or empty string is treated as the session for the default target for the top page.
methodName
stringThe full name of the method in the format
{domain}.{method}
.parametersAsJson
stringA JSON formatted string containing the parameters for the corresponding method.
Returns
Remarks
There could be multiple DevToolsProtocol
targets in a WebView.
Besides the top level page, iframes from different origin and web workers are also separate targets.
Attaching to these targets allows interaction with them.
When the DevToolsProtocol is attached to a target, the connection is identified by a sessionId.
To use this API, you must set the flatten
parameter to true when calling Target.attachToTarget
or Target.setAutoAttach
DevToolsProtocol
method.
Using Target.setAutoAttach
is recommended as that would allow you to attach to dedicated worker targets, which are not discoverable via other APIs like Target.getTargets
.
For more information about targets and sessions, navigate to Chrome DevTools Protocol - Target domain.
For more information about available methods, navigate to DevTools Protocol Viewer. The handler's Invoke method will be called when the method asynchronously completes. Invoke will be called with the method's return object as a JSON string.
CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat, Stream)
Captures an image of what WebView is displaying.
public Task CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat imageFormat, Stream imageStream)
Parameters
imageFormat
CoreWebView2CapturePreviewImageFormatThe format of the image to be captured.
imageStream
StreamThe stream to which the resulting image binary data is written.
Returns
Remarks
When CapturePreviewAsync finishes writing to the stream, the Invoke method on the provided handler parameter is called. This method fails if called before the first ContentLoading event. For example if this is called in the NavigationStarting event for the first navigation it will fail. For subsequent navigations, the method may not fail, but will not capture an image of a given webpage until the ContentLoading event has been fired for it. Any call to this method prior to that will result in a capture of the page being navigated away from.
- See Also
ClearServerCertificateErrorActionsAsync()
Clears all cached decisions to proceed with TLS certificate errors from the ServerCertificateErrorDetected event for all WebView2's sharing the same session.
public Task ClearServerCertificateErrorActionsAsync()
Returns
ClearVirtualHostNameToFolderMapping(string)
Clears a host name mapping for local folder that was added by SetVirtualHostNameToFolderMapping(string, string, CoreWebView2HostResourceAccessKind).
public void ClearVirtualHostNameToFolderMapping(string hostName)
Parameters
hostName
stringThe host name to be removed from the mapping.
- See Also
CloseDefaultDownloadDialog()
Close the default download dialog.
public void CloseDefaultDownloadDialog()
Remarks
Calling this method raises the IsDefaultDownloadDialogOpenChanged event if the dialog was open. No effect if the dialog is already closed.
CreateFromComICoreWebView2(nint)
Creates a CoreWebView2 object that wraps an existing COM ICoreWebView2 object. This allows interacting with the CoreWebView2 using .NET, even if it was originally created using COM.
public static CoreWebView2 CreateFromComICoreWebView2(nint value)
Parameters
value
nintPointer to a COM object that implements the ICoreWebView2 COM interface.
Returns
- CoreWebView2
Returns a .NET CoreWebView2 object that wraps the COM object.
Exceptions
- ArgumentNullException
Thrown when the provided COM pointer is null.
- InvalidComObjectException
Thrown when the value is not an ICoreWebView2 COM object and cannot be wrapped.
ExecuteScriptAsync(string)
Runs JavaScript code from the javaScript
parameter in the current top-level document rendered in the WebView.
public Task<string> ExecuteScriptAsync(string javaScript)
Parameters
javaScript
stringThe JavaScript code to be run in the current top-level document rendered in the WebView.
Returns
Examples
Remarks
If the result is undefined
, contains a reference cycle, or otherwise is not able to be encoded into JSON, the JSON null
value is returned as the "null"
string.
A function that has no explicit return value returns undefined
. If the script that was run throws an unhandled exception, then the result is also null
. This method is applied asynchronously. If the method is run after the NavigationStarting event during a navigation, the script runs in the new document when loading it, around the time ContentLoading is run. This operation works even if IsScriptEnabled is set to false
.
- See Also
ExecuteScriptWithResultAsync(string)
Runs JavaScript code from the javaScript
parameter in the current top-level document rendered in the WebView, The result of the execution is returned asynchronously in the CoreWebView2ExecuteScriptResult object which has methods and properties to obtain the successful result of script execution as well as any unhandled JavaScript exceptions.
public Task<CoreWebView2ExecuteScriptResult> ExecuteScriptWithResultAsync(string javaScript)
Parameters
javaScript
string
Returns
Examples
GetDevToolsProtocolEventReceiver(string)
Gets a DevTools Protocol event receiver that allows you to subscribe to a DevToolsProtocol event.
public CoreWebView2DevToolsProtocolEventReceiver GetDevToolsProtocolEventReceiver(string eventName)
Parameters
eventName
stringThe full name of the event in the format
{domain}.{event}
.
Returns
- CoreWebView2DevToolsProtocolEventReceiver
A Devtools Protocol event receiver.
Remarks
For more information about DevToolsProtocol events description and event args, navigate to DevTools Protocol Viewer.
GetFaviconAsync(CoreWebView2FaviconImageFormat)
Get the downloaded Favicon image for the current page and copy it to the image stream.
public Task<Stream> GetFaviconAsync(CoreWebView2FaviconImageFormat format)
Parameters
format
CoreWebView2FaviconImageFormatThe format to retrieve the Favicon in.
Returns
GoBack()
Navigates the WebView to the previous page in the navigation history.
public void GoBack()
GoForward()
Navigates the WebView to the next page in the navigation history.
public void GoForward()
Navigate(string)
Causes a navigation of the top level document to the specified URI.
public void Navigate(string uri)
Parameters
uri
stringThe URI to navigate to.
Examples
Remarks
For more information, navigate to Navigation event. Note that this operation starts a navigation and the corresponding NavigationStarting event is raised sometime after Navigate runs.
- See Also
NavigateToString(string)
Initiates a navigation to htmlContent
as source HTML of a new document.
public void NavigateToString(string htmlContent)
Parameters
htmlContent
stringA source HTML of a new document.
Examples
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
string htmlContent =
@"
Click me
";
webview.NavigateToString(htmlContent);
Remarks
The htmlContent
parameter may not be larger than 2 MB (2 * 1024 * 1024 bytes) in total size. The origin of the new page is about:blank
.
- See Also
NavigateWithWebResourceRequest(CoreWebView2WebResourceRequest)
Navigates using a constructed CoreWebView2WebResourceRequest object.
public void NavigateWithWebResourceRequest(CoreWebView2WebResourceRequest Request)
Parameters
Request
CoreWebView2WebResourceRequestThe constructed web resource object to provide post data or additional request headers during navigation.
Examples
Remarks
The headers in the CoreWebView2WebResourceRequest override headers added by WebView2 runtime except for Cookie headers. Method can only be either GET
or POST
. Provided post data will only be sent only if the method is POST
and the uri scheme is HTTP(S)
.
OpenDefaultDownloadDialog()
Open the default download dialog.
public void OpenDefaultDownloadDialog()
Remarks
If the dialog is opened before there are recent downloads, the dialog shows all past downloads for the current profile. Otherwise, the dialog shows only the recent downloads with a "See more" button for past downloads. Calling this method raises the IsDefaultDownloadDialogOpenChanged event if the dialog was closed. No effect if the dialog is already open.
OpenDevToolsWindow()
Opens the DevTools window for the current document in the WebView.
public void OpenDevToolsWindow()
Remarks
Does nothing if run when the DevTools window is already open.
OpenTaskManagerWindow()
Opens the Browser Task Manager view as a new window in the foreground.
public void OpenTaskManagerWindow()
Remarks
If the Browser Task Manager is already open, this will bring it into the foreground. WebView2 currently blocks the Shift+Esc shortcut for opening the task manager. An end user can open the browser task manager manually via the Browser task manager
entry of the DevTools window's title bar's context menu.
PostSharedBufferToScript(CoreWebView2SharedBuffer, CoreWebView2SharedBufferAccess, string)
Share a shared buffer object with script of the main frame in the WebView.
public void PostSharedBufferToScript(CoreWebView2SharedBuffer sharedBuffer, CoreWebView2SharedBufferAccess access, string additionalDataAsJson)
Parameters
sharedBuffer
CoreWebView2SharedBufferThe CoreWebView2SharedBuffer object to be shared with script.
access
CoreWebView2SharedBufferAccessThe desired CoreWebView2SharedBufferAccess given to script.
additionalDataAsJson
stringAdditional data to be send to script. If it is not null or empty string, and it is not a valid JSON string, ArgumentException will be thrown.
Examples
Remarks
The script will receive a sharedbufferreceived
event from chrome.webview.
The event arg for that event will have the following methods and properties.
Property | Description |
---|---|
getBuffer() | A method that returns an ArrayBuffer object with the backing content from the shared buffer. |
additionalData | An object as the result of parsing additionalDataAsJson as JSON string. This property will be undefined if additionalDataAsJson is nullptr or empty string. |
source | With a value set as chrome.webview object. |
If access
is ReadOnly, the script will only have read access to the buffer.
If the script tries to modify the content in a read only buffer, it will cause an access violation in WebView renderer process and crash the renderer process.
If the shared buffer is already closed, the API throws COMException with error code of RO_E_CLOSED
.
The script code should call chrome.webview.releaseBuffer
with the shared buffer as the parameter to release underlying resources as soon as it does not need access to the shared buffer any more.
The application can post the same shared buffer object to multiple web pages or iframes, or post to the same web page or iframe multiple times.
Each PostSharedBufferToScript
will create a separate ArrayBuffer object with its own view of the memory and is separately released.
The underlying shared memory will be released when all the views are released.
Sharing a buffer to script has security risk. You should only share buffer with trusted site. If a buffer is shared to a untrusted site, possible sensitive information could be leaked. If a buffer is shared as modifiable by the script and the script modifies it in an unexpected way, it could result in corrupted data that might even crash the application.
The example code shows how to send data to script for one time read only consumption.
PostWebMessageAsJson(string)
Posts the specified webMessageAsJson
to the top level document in this WebView.
public void PostWebMessageAsJson(string webMessageAsJson)
Parameters
webMessageAsJson
stringThe web message to be posted to the top level document in this WebView.
Examples
Runs the message event of the window.chrome.webview
of the top-level document. JavaScript in that document may subscribe and unsubscribe to the event using the following code:
window.chrome.webview.addEventListener('message', handler)
window.chrome.webview.removeEventListener('message', handler)
Remarks
The event args is an instance of MessageEvent
. The IsWebMessageEnabled setting must be true
or the message will not be sent. The event arg's data
property of the event arg is the webMessageAsJson
string parameter parsed as a JSON string into a JavaScript object. The event arg's source
property of the event arg is a reference to the window.chrome.webview
object. For information about sending messages from the HTML document in the WebView to the host, navigate to WebMessageReceived. The message is sent asynchronously. If a navigation occurs before the message is posted to the page, the message is not be sent.
- See Also
PostWebMessageAsString(string)
Posts a message that is a simple string rather than a JSON string representation of a JavaScript object.
public void PostWebMessageAsString(string webMessageAsString)
Parameters
webMessageAsString
stringThe web message to be posted to the top level document in this WebView.
Remarks
This behaves in exactly the same manner as PostWebMessageAsJson(string), but the data
property of the event arg of the window.chrome.webview
message is a string with the same value as webMessageAsString
. Use this instead of PostWebMessageAsJson(string) if you want to communicate using simple strings rather than JSON objects.
- See Also
PrintAsync(CoreWebView2PrintSettings)
Print the current web page asynchronously to the specified printer with the provided settings.
public Task<CoreWebView2PrintStatus> PrintAsync(CoreWebView2PrintSettings printSettings)
Parameters
printSettings
CoreWebView2PrintSettings
Returns
Examples
Remarks
See CoreWebView2PrintSettings for description of settings. Passing null for printSettings
results in default print settings used.
The method will return CoreWebView2PrintStatus as PrinterUnavailable if printerName
doesn't match with the name of any installed printers on the user OS.
The method will throw ArgumentException if the caller provides invalid settings for a given printer.
The async Print operation completes when it finishes printing to the printer. Only one Printing
operation can be in progress at a time. If Print
is called while a PrintAsync(CoreWebView2PrintSettings) or PrintToPdfAsync(string, CoreWebView2PrintSettings) or PrintToPdfStreamAsync(CoreWebView2PrintSettings) job is in progress, Task<TResult> throws exception. This is only for printing operation on one webview.
Error | PrintStatus | Notes |
---|---|---|
No | Succeeded | Print operation succeeded. |
No | PrinterUnavailable | If specified printer is not found or printer status is not available, offline or error state. |
No | OtherError | Print operation is failed. |
ArgumentException | OtherError | If the caller provides invalid settings for the specified printer. |
Exception | OtherError | Print operation is failed as printing job already in progress. |
PrintToPdfAsync(string, CoreWebView2PrintSettings)
Print the current page to PDF asynchronously with the provided settings.
public Task<bool> PrintToPdfAsync(string ResultFilePath, CoreWebView2PrintSettings printSettings = null)
Parameters
ResultFilePath
stringprintSettings
CoreWebView2PrintSettings
Returns
Remarks
See CoreWebView2PrintSettings for description of settings. Passing null for printSettings
results in default print settings used.
Use resultFilePath
to specify the path to the PDF file. The host should provide an absolute path, including file name. If the path points to an existing file, the file will be overwritten. If the path is not valid, the method fails.
The async PrintToPdf operation completes when the data has been written to the PDF file. If the application exits before printing is complete, the file is not saved. Only one Printing
operation can be in progress at a time.
If PrintToPdf is called while a PrintToPdf
or PrintToPdfStream
or Print
operation is in progress, the operation completes and returns false.
PrintToPdfStreamAsync(CoreWebView2PrintSettings)
Provides the Pdf data of current web page asynchronously for the provided settings.
public Task<Stream> PrintToPdfStreamAsync(CoreWebView2PrintSettings printSettings)
Parameters
printSettings
CoreWebView2PrintSettings
Returns
Examples
Remarks
Stream will be rewound to the start of the pdf data.
See CoreWebView2PrintSettings for description of settings. Passing null for printSettings
results in default print settings used.
The async PrintToPdfStream operation completes when it finishes writing to the stream. Only one Printing
operation can be in progress at a time. If PrintToPdfStreamAsync(CoreWebView2PrintSettings) is called while a PrintToPdfStreamAsync(CoreWebView2PrintSettings) or PrintToPdfAsync(string, CoreWebView2PrintSettings) or PrintAsync(CoreWebView2PrintSettings) job is in progress, the Task<TResult> throws an exception. This is only for printing operation on one webview.
Reload()
Reloads the current page.
public void Reload()
Remarks
This is similar to navigating to the URI of current top level document including all navigation events firing and respecting any entries in the HTTP cache. But, the back or forward history will not be modified.
RemoveHostObjectFromScript(string)
Removes the host object specified by the name so that it is no longer accessible from JavaScript code in the WebView.
public void RemoveHostObjectFromScript(string name)
Parameters
name
stringThe name of the host object to be removed.
Remarks
While new access attempts are denied, if the object is already obtained by JavaScript code in the WebView, the JavaScript code continues to have access to that object. Running this method for a name that is already removed or never added fails.
RemoveScriptToExecuteOnDocumentCreated(string)
Removes the corresponding JavaScript added via AddScriptToExecuteOnDocumentCreatedAsync(string) with the specified script ID.
public void RemoveScriptToExecuteOnDocumentCreated(string id)
Parameters
id
stringThe ID corresponds to the JavaScript code to be removed from the list of scripts.
RemoveWebResourceRequestedFilter(string, CoreWebView2WebResourceContext)
Removes a matching WebResource filter that was previously added for the WebResourceRequested event.
public void RemoveWebResourceRequestedFilter(string uri, CoreWebView2WebResourceContext ResourceContext)
Parameters
uri
stringAn URI to at which a web resource filter was added.
ResourceContext
CoreWebView2WebResourceContextA previously added resource context filter to be removed.
Remarks
If the same filter was added multiple times, then it must need to be removed as many times as it was added for the removal to be effective.
Exceptions
- ArgumentException
A filter that was never added.
- See Also
RemoveWebResourceRequestedFilter(string, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds)
Removes a matching WebResource filter that was previously added for the WebResourceRequested event.
public void RemoveWebResourceRequestedFilter(string uri, CoreWebView2WebResourceContext ResourceContext, CoreWebView2WebResourceRequestSourceKinds RequestSourceKinds)
Parameters
uri
stringAn URI to be added to the WebResourceRequested event.
ResourceContext
CoreWebView2WebResourceContextA resource context filter to be added to the WebResourceRequested event.
RequestSourceKinds
CoreWebView2WebResourceRequestSourceKindsA request source filter to be added to the WebResourceRequested event.
Resume()
Resumes the WebView so that it resumes activities on the web page.
public void Resume()
Examples
Remarks
This API can be called while the WebView2 controller is invisible.
The app can interact with the WebView immediately after Resume().
WebView will be automatically resumed when it becomes visible.
SetVirtualHostNameToFolderMapping(string, string, CoreWebView2HostResourceAccessKind)
Sets a mapping between a virtual host name and a folder path to make available to web sites via that host name.
public void SetVirtualHostNameToFolderMapping(string hostName, string folderPath, CoreWebView2HostResourceAccessKind accessKind)
Parameters
hostName
stringA virtual host name.
folderPath
stringA folder path name to be mapped to the virtual host name. The length must not exceed the Windows MAX_PATH limit.
accessKind
CoreWebView2HostResourceAccessKindThe level of access to resources under the virtual host from other sites.
Examples
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
webView.Source = new Uri("https://appassets.example/index.html");
This in an example on how to embed a local image. For more information see NavigateToString(string).
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
string c_navString = "";
webview.NavigateToString(c_navString);
Remarks
After setting the mapping, documents loaded in the WebView can use HTTP or HTTPS URLs at the specified host name specified by hostName
to access files in the local folder specified by folderPath
.
This mapping applies to both top-level document and iframe navigations as well as subresource references from a document. This also applies to dedicated and shared worker scripts but does not apply to service worker scripts.
Due to a current implementation limitation, media files accessed using virtual host name can be very slow to load.
As the resource loaders for the current page might have already been created and running, changes to the mapping might not be applied to the current page and a reload of the page is needed to apply the new mapping.
Both absolute and relative paths are supported for folderPath
. Relative paths are interpreted as relative to the folder where the exe of the app is in.
For example, after calling SetVirtualHostNameToFolderMapping("appassets.example", "assets", CoreWebView2HostResourceAccessKind.Deny);
, navigating to https://appassets.example/my-local-file.html
will show content from my-local-file.html in the assets subfolder located on disk under the same path as the app's executable file.
DOM elements that want to reference local files will have their host reference virtual host in the source. If there are multiple folders being used, define one unique virtual host per folder.
You should typically choose virtual host names that are never used by real sites.
If you own a domain such as example.com
, another option is to use a subdomain reserved for the app (like my-app.example.com
).
[RFC 6761](https://tools.ietf.org/html/rfc6761) has reserved several special-use domain names that are guaranteed to not be used by real sites (for example, .example
, .test
, and .invalid
).
Note that using .local
as the top-level domain name will work but can cause a delay during navigations. You should avoid using .local
if you can.
Apps should use distinct domain names when mapping folder from different sources that should be isolated from each other. For instance, the app might use app-file.example for files that ship as part of the app, and book1.example might be used for files containing books from a less trusted source that were previously downloaded and saved to the disk by the app.
The host name used in the APIs is canonicalized using Chromium's host name parsing logic before being used internally. For more information see [HTML5 2.6 URLs](https://dev.w3.org/html5/spec-LC/urls.html).
All host names that are canonicalized to the same string are considered identical.
For example, EXAMPLE.COM
and example.com
are treated as the same host name.
An international host name and its Punycode-encoded host name are considered the same host name. There is no DNS resolution for host name and the trailing '.' is not normalized as part of canonicalization.
Therefore example.com
and example.com.
are treated as different host names. Similarly, virtual-host-name
and virtual-host-name.example.com
are treated as different host names even if the machine has a DNS suffix of example.com
.
Specify the minimal cross-origin access necessary to run the app. If there is not a need to access local resources from other origins, use Deny.
- See Also
ShowPrintUI()
Opens the browser print preview dialog to print the current web page
public void ShowPrintUI()
ShowPrintUI(CoreWebView2PrintDialogKind)
Opens the print dialog to print the current web page.
public void ShowPrintUI(CoreWebView2PrintDialogKind printDialogKind)
Parameters
printDialogKind
CoreWebView2PrintDialogKind
Examples
Remarks
See CoreWebView2PrintDialogKind for descriptions of print dialog kinds.
Invoking browser or system print dialog doesn't open new print dialog if it is already open.
Stop()
Stops all navigations and pending resource fetches.
public void Stop()
Remarks
Does not stop scripts.
TrySuspendAsync()
An app may call this API to have the WebView2 consume less memory.
public Task<bool> TrySuspendAsync()
Returns
Examples
Remarks
This is useful when a Win32 app becomes invisible, or when a Universal Windows Platform app is being suspended, during the suspended event handler before completing the suspended event.
The IsVisible property must be false when the API is called. Otherwise, the API throws COMException with error code of HRESULT_FROM_WIN32(ERROR_INVALID_STATE)
.
Suspending is similar to putting a tab to sleep in the Edge browser. Suspending pauses WebView script timers and animations, minimizes CPU usage for the associated browser renderer process and allows the operating system to reuse the memory that was used by the renderer process for other processes.
Note that Suspend is best effort and considered completed successfully once the request is sent to browser renderer process. If there is a running script, the script will continue to run and the renderer process will be suspended after that script is done.
See Sleeping Tabs FAQ for conditions that might prevent WebView from being suspended. In those situations, the result of the async task is false.
The WebView will be automatically resumed when it becomes visible. Therefore, the app normally does not have to call Resume() explicitly.
The app can call Resume() and then TrySuspendAsync() periodically for an invisible WebView so that the invisible WebView can sync up with latest data and the page ready to show fresh content when it becomes visible.
All WebView APIs can still be accessed when a WebView is suspended. Some APIs like Navigate will auto resume the WebView. To avoid unexpected auto resume, check IsSuspended property before calling APIs that might change WebView state.
Events
BasicAuthenticationRequested
BasicAuthenticationRequested event is raised when WebView encounters a Basic HTTP Authentication request as described in https://developer.mozilla.org/docs/Web/HTTP/Authentication, a Digest HTTP Authentication request as described in https://developer.mozilla.org/docs/Web/HTTP/Headers/Authorization#digest, an NTLM authentication or a Proxy Authentication request.
public event EventHandler<CoreWebView2BasicAuthenticationRequestedEventArgs> BasicAuthenticationRequested
Event Type
Examples
Remarks
The host can provide a response with credentials for the authentication or cancel the request. If the host sets the Cancel property to false but does not provide either UserName or Password properties on the Response property, then WebView2 will show the default authentication challenge dialog prompt to the user.
ClientCertificateRequested
ClientCertificateRequested is raised when WebView2 is making a request to an HTTP server that needs a client certificate for HTTP authentication. Read more about HTTP client certificates at RFC 8446 The Transport Layer Security (TLS) Protocol Version 1.3.
public event EventHandler<CoreWebView2ClientCertificateRequestedEventArgs> ClientCertificateRequested
Event Type
Examples
Remarks
The host have several options for responding to client certificate requests:
Scenario | Handled | Cancel | SelectedCertificate |
---|---|---|---|
Respond to server with a certificate | True | False | MutuallyTrustedCertificate value |
Respond to server without certificate | True | False | null |
Display default client certificate selection dialog prompt | False | False | n/a |
Cancel the request | n/a | True | n/a |
If the host don't handle the event, WebView2 will show the default client certificate selection dialog prompt to the user.
ContainsFullScreenElementChanged
ContainsFullScreenElementChanged is raised when the ContainsFullScreenElement property changes.
public event EventHandler<object> ContainsFullScreenElementChanged
Event Type
Remarks
An HTML element inside the WebView may enter fullscreen to the size of the WebView or leave fullscreen. This event is useful when, for example, a video element requests to go fullscreen. The listener of this event may resize the WebView in response.
- See Also
ContentLoading
ContentLoading is raised before any content is loaded, including scripts added with AddScriptToExecuteOnDocumentCreatedAsync(string). ContentLoading is not raised if a same page navigation occurs (such as through fragment navigations or history.pushState
navigations).
public event EventHandler<CoreWebView2ContentLoadingEventArgs> ContentLoading
Event Type
Remarks
This operation follows the NavigationStarting and SourceChanged events and precedes the HistoryChanged and NavigationCompleted events.
- See Also
ContextMenuRequested
ContextMenuRequested is raised when a context menu is requested by the user and the content inside WebView hasn't disabled context menus.
public event EventHandler<CoreWebView2ContextMenuRequestedEventArgs> ContextMenuRequested
Event Type
Examples
Remarks
The host has the option to create their own context menu with the information provided in the event or can add items to or remove items from WebView context menu. If the host doesn't handle the event, WebView will display the default context menu.
DOMContentLoaded
DOMContentLoaded is raised when the initial HTML document has been parsed.
public event EventHandler<CoreWebView2DOMContentLoadedEventArgs> DOMContentLoaded
Event Type
Examples
Remarks
This aligns with the the document's DOMContentLoaded event in HTML.
DocumentTitleChanged
DocumentTitleChanged is raised when the DocumentTitle property changes and may be raised before or after the NavigationCompleted event.
public event EventHandler<object> DocumentTitleChanged
Event Type
Examples
- See Also
DownloadStarting
DownloadStarting is raised when a download has begun, blocking the default download dialog, but not blocking the progress of the download.
public event EventHandler<CoreWebView2DownloadStartingEventArgs> DownloadStarting
Event Type
Examples
Remarks
The host can choose to cancel a download, change the result file path, and hide the default download dialog. If download is not handled or canceled, the download is saved to the default path after the event completes with default download dialog shown.
FaviconChanged
Raised when the Favicon has changed. This can include when a new page is loaded and thus by default no icon is set or the icon is set for the page by DOM or JavaScript.
public event EventHandler<object> FaviconChanged
Event Type
Remarks
The first argument is the Webview2 which saw the changed Favicon and the second is null.
FrameCreated
FrameCreated is raised when a new iframe is created. Handle this event to get access to CoreWebView2Frame objects.
public event EventHandler<CoreWebView2FrameCreatedEventArgs> FrameCreated
Event Type
Remarks
Use the Destroyed to listen for when this iframe goes away.
- See Also
FrameNavigationCompleted
FrameNavigationCompleted is raised when a child frame has completely loaded (body.onload
has been raised) or loading stopped with error.
public event EventHandler<CoreWebView2NavigationCompletedEventArgs> FrameNavigationCompleted
Event Type
FrameNavigationStarting
FrameNavigationStarting is raised when a child frame in the WebView requests permission to navigate to a different URI.
public event EventHandler<CoreWebView2NavigationStartingEventArgs> FrameNavigationStarting
Event Type
Remarks
Redirects raise this operation as well, and the navigation id is the same as the original one. You may block corresponding navigations until the event handler returns.
HistoryChanged
HistoryChanged is raised for changes to joint session history, which consists of top-level and manual frame navigations.
public event EventHandler<object> HistoryChanged
Event Type
Remarks
Use HistoryChanged to verify that the CanGoBack or CanGoForward value has changed. HistoryChanged is also raised for using GoBack() or GoForward(). HistoryChanged is raised after SourceChanged and ContentLoading. CanGoBack is false for navigations initiated through CoreWebView2Frame APIs if there has not yet been a user gesture.
- See Also
IsDefaultDownloadDialogOpenChanged
Raised when the IsDefaultDownloadDialogOpen property changes.
public event EventHandler<object> IsDefaultDownloadDialogOpenChanged
Event Type
Remarks
This event comes after the DownloadStarting event. Setting the Handled property disables the default download dialog and ensures that this event is never raised.
IsDocumentPlayingAudioChanged
IsDocumentPlayingAudioChanged is raised when document starts or stops playing audio.
public event EventHandler<object> IsDocumentPlayingAudioChanged
Event Type
Examples
IsMutedChanged
IsMutedChanged is raised when the mute state changes.
public event EventHandler<object> IsMutedChanged
Event Type
Examples
LaunchingExternalUriScheme
LaunchingExternalUriScheme is raised when a navigation request is made to a URI scheme that is registered with the OS.
public event EventHandler<CoreWebView2LaunchingExternalUriSchemeEventArgs> LaunchingExternalUriScheme
Event Type
Examples
Remarks
The LaunchingExternalUriScheme event handler may suppress the default dialog or replace the default dialog with a custom dialog. If a CoreWebView2Deferral is not taken on the event args, the external URI scheme launch is blocked until the event handler returns. If a deferral is taken, the external URI scheme launch is blocked until the CoreWebView2Deferral is completed. The host also has the option to cancel the URI scheme launch.
The NavigationStarting and NavigationCompleted events will be raised, regardless of whether the Cancel property is set to true
or false
.
The NavigationCompleted event will be raised with the IsSuccess property set to false
and the WebErrorStatus property set to ConnectionAborted regardless of whether the host sets the Cancel property.
The SourceChanged, ContentLoading and HistoryChanged events will not be raised for this navigation to the external URI scheme regardless of the Cancel property.
The LaunchingExternalUriScheme event will be raised after the NavigationStarting event and before the NavigationCompleted event.
The default CoreWebView2Settings will also be updated upon navigation to an external URI scheme. If a setting on the CoreWebView2Settings interface has been changed, navigating to an external URI scheme will trigger the CoreWebView2Settings to update.
The WebView2 may not display the default dialog based on user settings, browser settings, and whether the origin is determined as a trustworthy origin; however, the event will still be raised.
If the request is initiated by a cross-origin frame without a user gesture, the request will be blocked and the LaunchingExternalUriScheme
event will not be raised. A URI scheme may be blocked for safety reasons. In this case the LaunchingExternalUriScheme
event will not be raised. The default dialog may show an "always allow" checkbox which allows the user to opt-in to relaxed security (i.e. skipping future default dialogs) for the combination of the URI scheme and the origin of the page initiating this external URI scheme launch. The checkbox is offered so long as the group policy to show the checkbox is not explicitly disabled and there is a trustworthy initiating origin. If the user has checked this box, future attempts to launch this URI scheme will still raise the event.
NavigationCompleted
NavigationCompleted is raised when the WebView has completely loaded (body.onload
has been raised) or loading stopped with error.
public event EventHandler<CoreWebView2NavigationCompletedEventArgs> NavigationCompleted
Event Type
Examples
NavigationStarting
NavigationStarting is raised when the WebView main frame is requesting permission to navigate to a different URI.
public event EventHandler<CoreWebView2NavigationStartingEventArgs> NavigationStarting
Event Type
Examples
Remarks
Redirects raise this event as well, and the navigation id is the same as the original one. You may block corresponding navigations until the event handler returns.
NewWindowRequested
NewWindowRequested is raised when content inside the WebView requests to open a new window, such as through window.open()
.
public event EventHandler<CoreWebView2NewWindowRequestedEventArgs> NewWindowRequested
Event Type
Remarks
The app can pass a target WebView that is considered the opened window or mark the event as Handled, in which case WebView2 does not open a window.
If either Handled
or NewWindow properties are not set, the target content will be opened on a popup window.
If a deferral is not taken on the event args, scripts that resulted in the new window that are requested are blocked until the event handler returns. If a deferral is taken, then scripts are blocked until the deferral is completed.
On Hololens 2, if the NewWindow property is not set and the Handled property is not set to true
, the WebView2 will navigate to the Uri.
If either of these properties are set, the WebView2 will not navigate to the Uri and the the NewWindowRequested event will continue as normal.
PermissionRequested
PermissionRequested is raised when content in a WebView requests permission to access some privileged resources.
public event EventHandler<CoreWebView2PermissionRequestedEventArgs> PermissionRequested
Event Type
Remarks
If a deferral is not taken on the event args, the subsequent scripts are blocked until the event handler returns. If a deferral is taken, the scripts are blocked until the deferral is completed.
ProcessFailed
ProcessFailed is raised when a WebView process ends unexpectedly or becomes unresponsive.
public event EventHandler<CoreWebView2ProcessFailedEventArgs> ProcessFailed
Event Type
Examples
Remarks
ProcessFailed
is raised when any of the processes in the WebView2 Process Group encounters one of the following conditions:
Condition | Details |
---|---|
Unexpected exit | The process indicated by the event args has exited unexpectedly (usually due to a crash). The failure might or might not be recoverable, and some failures are auto-recoverable. |
Unresponsiveness | The process indicated by the event args has become unresponsive to user input. This is only reported for renderer processes, and will run every few seconds until the process becomes responsive again. |
Note: When the failing process is the browser process, a BrowserProcessExited event will run too.
Your application can use CoreWebView2ProcessFailedEventArgs to identify which condition and process the event is for, and to collect diagnostics and handle recovery if necessary. For more details about which cases need to be handled by your application, see CoreWebView2ProcessFailedKind.
ScriptDialogOpening
ScriptDialogOpening is raised when a JavaScript dialog (alert
, confirm
, prompt
, or beforeunload
) displays for the WebView.
public event EventHandler<CoreWebView2ScriptDialogOpeningEventArgs> ScriptDialogOpening
Event Type
Remarks
This event only is raised if the AreDefaultScriptDialogsEnabled property is set to false
. This event suppresses dialogs or replaces default dialogs with custom dialogs.
If a deferral is not taken on the event args, the subsequent scripts are blocked until the event handler returns. If a deferral is taken, the scripts are blocked until the deferral is completed.
- See Also
ServerCertificateErrorDetected
The ServerCertificateErrorDetected event is raised when the WebView2 cannot verify server's digital certificate while loading a web page.
public event EventHandler<CoreWebView2ServerCertificateErrorDetectedEventArgs> ServerCertificateErrorDetected
Event Type
Examples
Remarks
This event will raise for all web resources and follows the WebResourceRequested event.
If you don't handle the event, WebView2 will show the default TLS interstitial error page to the user for navigations, and for non-navigations the web request is cancelled.
Note that WebView2 before raising ServerCertificateErrorDetected
raises a NavigationCompleted event with IsSuccess as FALSE and any of the below WebErrorStatuses that indicate a certificate failure.
- CertificateCommonNameIsIncorrect
- CertificateExpired
- ClientCertificateContainsErrors
- CertificateRevoked
- CertificateIsInvalid
For more details see IsSuccess and handle ServerCertificateErrorDetected event or show the default TLS interstitial error page to the user according to the app needs.
WebView2 caches the response when action is AlwaysAllow for the RequestUri's host and the server certificate in the session and the ServerCertificateErrorDetected event won't be raised again.
To raise the event again you must clear the cache using ClearServerCertificateErrorActionsAsync().
SourceChanged
SourceChanged is raised when the Source property changes.
public event EventHandler<CoreWebView2SourceChangedEventArgs> SourceChanged
Event Type
Remarks
SourceChanged is raised when navigating to a different site or fragment navigations. It is not raised for other types of navigations such as page refreshes or history.pushState
with the same URL as the current page. This event is raised before ContentLoading for navigation to a new document.
- See Also
StatusBarTextChanged
StatusBarTextChanged event is raised when the text in the Window.statusbar changes. When the event is fired use the property StatusBarText to get the current statusbar text.
public event EventHandler<object> StatusBarTextChanged
Event Type
Remarks
Events which cause causes can be anything from hover, url events, and others. There is not a finite list on how to cause the statusbar to change. The developer must create the status bar and set the text.
WebMessageReceived
WebMessageReceived is raised when the IsWebMessageEnabled setting is set and the top-level document of the WebView runs window.chrome.webview.postMessage
or window.chrome.webview.postMessageWithAdditionalObjects
.
public event EventHandler<CoreWebView2WebMessageReceivedEventArgs> WebMessageReceived
Event Type
Remarks
The postMessage
function is void postMessage(object)
where object is any object supported by JSON conversion.
When postMessage
is called, the handler's Invoke method will be called with the object
parameter postMessage
converted to a JSON string.
If the same page calls postMessage
multiple times, the corresponding WebMessageReceived
events are guaranteed to be fired in the same order. However, if multiple frames call postMessage
, there is no guaranteed order. In addition, WebMessageReceived
events caused by calls to postMessage
are not guaranteed to be sequenced with events caused by DOM APIs. For example, if the page runs
chrome.webview.postMessage("message");
window.open();
then the NewWindowRequested event might be fired before the WebMessageReceived
event. If you need the WebMessageReceived
event to happen before anything else, then in the WebMessageReceived
handler you can post a message back to the page and have the page wait until it receives that message before continuing.
WebResourceRequested
WebResourceRequested is raised when the WebView is performing a URL request to a matching URL and resource context filter that was added with AddWebResourceRequestedFilter(string, CoreWebView2WebResourceContext).
public event EventHandler<CoreWebView2WebResourceRequestedEventArgs> WebResourceRequested
Event Type
Remarks
At least one filter must be added for the event to be raised. The web resource requested may be blocked until the event handler returns if a deferral is not taken on the event args. If a deferral is taken, then the web resource requested is blocked until the deferral is completed.
If this event is subscribed in the NewWindowRequested handler it should be called after the new window is set. For more details see NewWindow.
This event is by default raised for file, http, and https URI schemes. This is also raised for registered custome URI schemes. See CoreWebView2CustomSchemeRegistration for more details.
- See Also
WebResourceResponseReceived
WebResourceResponseReceived is raised when the WebView receives the response for a request for a web resource (any URI resolution performed by the WebView; such as HTTP/HTTPS, file and data requests from redirects, navigations, declarations in HTML, implicit Favicon lookups, and fetch API usage in the document).
public event EventHandler<CoreWebView2WebResourceResponseReceivedEventArgs> WebResourceResponseReceived
Event Type
Examples
Remarks
The host app can use this event to view the actual request and response for a web resource. There is no guarantee about the order in which the WebView processes the response and the host app's handler runs. The app's handler will not block the WebView from processing the response. The event args include the CoreWebView2WebResourceRequest as sent by the wire and CoreWebView2WebResourceResponse received, including any additional headers added by the network stack that were not be included as part of the associated WebResourceRequested event, such as Authentication headers.
WindowCloseRequested
WindowCloseRequested is raised when content inside the WebView requested to close the window, such as after window.close()
is run.
public event EventHandler<object> WindowCloseRequested
Event Type
Remarks
The app should close the WebView and related app window if that makes sense to the app. After the first window.close() call, this event may not fire for any immediate back to back window.close() calls.