Partager via


CoreWebView2 Class

Definition

WebView2 enables you to host web content using the latest Microsoft Edge browser and web technology.

public class CoreWebView2
type CoreWebView2 = class
Public Class CoreWebView2
Inheritance
CoreWebView2

Properties

BrowserProcessId

Gets the process ID of the browser process that hosts the WebView.

CanGoBack

true if the WebView is able to navigate to a previous page in the navigation history.

CanGoForward

true if the WebView is able to navigate to a next page in the navigation history.

ContainsFullScreenElement

Indicates if the WebView contains a fullscreen HTML element.

CookieManager

Gets the CoreWebView2CookieManager object associated with this CoreWebView2.

CustomDataPartitionId

Gets or sets the custom data partition id of the WebView.

DefaultDownloadDialogCornerAlignment

The default download dialog corner alignment.

DefaultDownloadDialogMargin

The default download dialog margin relative to the WebView corner specified by DefaultDownloadDialogCornerAlignment.

DocumentTitle

Gets the title for the current top-level document.

Environment

Exposes the CoreWebView2Environment used to create this CoreWebView2.

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.

FrameId

The unique identifier of the main frame. It's the same kind of ID as with the FrameId and FrameId.

IsDefaultDownloadDialogOpen

True if the default download dialog is currently open.

IsDocumentPlayingAudio

Indicates whether any audio output from this CoreWebView2 is playing. true if audio is playing even if IsMuted is true.

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.

IsSuspended

Whether WebView is suspended.

MemoryUsageTargetLevel

Desired CoreWebView2MemoryUsageTargetLevel of a WebView.

Profile

The associated CoreWebView2Profile object of CoreWebView2.

Settings

Gets the CoreWebView2Settings object contains various modifiable settings for the running WebView.

Source

Gets the URI of the current top level document.

StatusBarText

The current text of the statusbar as defined by Window.statusbar.

Methods

AddHostObjectToScript(String, Object)

Adds the provided host object to script running in the WebView with the specified name.

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.

AddWebResourceRequestedFilter(String, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds)
AddWebResourceRequestedFilter(String, CoreWebView2WebResourceContext)

Warning: This method is deprecated and does not behave as expected for iframes. Please use AddWebResourceRequestedFilter(String, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds) instead. Adds a URI and resource context filter for the WebResourceRequested event.

CallDevToolsProtocolMethodAsync(String, String)

Runs an asynchronous DevToolsProtocol method.

CallDevToolsProtocolMethodForSessionAsync(String, String, String)

Runs an asynchronous DevToolsProtocol method for a specific session of an attached target.

CapturePreviewAsync(CoreWebView2CapturePreviewImageFormat, Stream)

Captures an image of what WebView is displaying.

ClearServerCertificateErrorActionsAsync()

Clears all cached decisions to proceed with TLS certificate errors from the ServerCertificateErrorDetected event for all WebView2's sharing the same session.

ClearVirtualHostNameToFolderMapping(String)

Clears a host name mapping for local folder that was added by SetVirtualHostNameToFolderMapping(String, String, CoreWebView2HostResourceAccessKind).

CloseDefaultDownloadDialog()

Close the default download dialog.

CreateFromComICoreWebView2(IntPtr)

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.

ExecuteScriptAsync(String)

Runs JavaScript code from the javaScript parameter in the current top-level document rendered in the WebView.

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.

GetComICoreWebView2()

Returns the existing COM ICoreWebView2 object underlying this .NET CoreWebView2 object. This allows interacting with the WebView2 control using COM APIs, even if the control was originally created using .NET.

GetDevToolsProtocolEventReceiver(String)

Gets a DevTools Protocol event receiver that allows you to subscribe to a DevToolsProtocol event.

GetFaviconAsync(CoreWebView2FaviconImageFormat)

Get the downloaded Favicon image for the current page and copy it to the image stream.

GoBack()

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

GoForward()

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

Navigate(String)

Causes a navigation of the top level document to the specified URI.

NavigateToString(String)

Initiates a navigation to htmlContent as source HTML of a new document.

NavigateWithWebResourceRequest(CoreWebView2WebResourceRequest)

Navigates using a constructed CoreWebView2WebResourceRequest object.

OpenDefaultDownloadDialog()

Open the default download dialog.

OpenDevToolsWindow()

Opens the DevTools window for the current document in the WebView.

OpenTaskManagerWindow()

Opens the Browser Task Manager view as a new window in the foreground.

PostSharedBufferToScript(CoreWebView2SharedBuffer, CoreWebView2SharedBufferAccess, String)

Share a shared buffer object with script of the main frame in the WebView.

PostWebMessageAsJson(String, List<Object>)

Same as PostWebMessageAsJson(String), but also has support for posting DOM objects to page content.

PostWebMessageAsJson(String)

Posts the specified webMessageAsJson to the top level document in this WebView.

PostWebMessageAsJsonWithAdditionalObjects(String, List<Object>)

Same as PostWebMessageAsJson(String), but also has support for posting DOM objects to page content.

PostWebMessageAsString(String)

Posts a message that is a simple string rather than a JSON string representation of a JavaScript object.

PrintAsync(CoreWebView2PrintSettings)

Print the current web page asynchronously to the specified printer with the provided settings.

PrintToPdfAsync(String, CoreWebView2PrintSettings)

Print the current page to PDF asynchronously with the provided settings.

PrintToPdfStreamAsync(CoreWebView2PrintSettings)

Provides the Pdf data of current web page asynchronously for the provided settings.

Reload()

Reloads the current page.

RemoveHostObjectFromScript(String)

Removes the host object specified by the name so that it is no longer accessible from JavaScript code in the WebView.

RemoveScriptToExecuteOnDocumentCreated(String)

Removes the corresponding JavaScript added via AddScriptToExecuteOnDocumentCreatedAsync(String) with the specified script ID.

RemoveWebResourceRequestedFilter(String, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds)

Removes a matching WebResource filter that was previously added for the WebResourceRequested event. If the same filter was added multiple times, then it must be removed as many times as it was added for the removal to be effective. Returns E_INVALIDARG for a filter that was not added or is already removed. If the filter was added for multiple requestSourceKinds and removed just for one of them the filter remains for the non-removed requestSourceKinds.

RemoveWebResourceRequestedFilter(String, CoreWebView2WebResourceContext)

Warning: This method and CoreWebView2.AddWebResourceRequestedFilter(string, CoreWebView2WebResourceContext) are deprecated. Please use AddWebResourceRequestedFilter(String, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds) and RemoveWebResourceRequestedFilter(String, CoreWebView2WebResourceContext, CoreWebView2WebResourceRequestSourceKinds) instead. Removes a matching WebResource filter that was previously added for the WebResourceRequested event.

Resume()

Resumes the WebView so that it resumes activities on the web page.

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.

ShowPrintUI()

Opens the browser print preview dialog to print the current web page

ShowPrintUI(CoreWebView2PrintDialogKind)

Opens the print dialog to print the current web page.

ShowSaveAsUIAsync()
Stop()

Stops all navigations and pending resource fetches.

TrySuspendAsync()

An app may call this API to have the WebView2 consume less memory.

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.

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.

ContainsFullScreenElementChanged

ContainsFullScreenElementChanged is raised when the ContainsFullScreenElement property changes.

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

ContextMenuRequested

ContextMenuRequested is raised when a context menu is requested by the user and the content inside WebView hasn't disabled context menus.

DocumentTitleChanged

DocumentTitleChanged is raised when the DocumentTitle property changes and may be raised before or after the NavigationCompleted event.

DOMContentLoaded

DOMContentLoaded is raised when the initial HTML document has been parsed.

DownloadStarting

DownloadStarting is raised when a download has begun, blocking the default download dialog, but not blocking the progress of the download.

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.

FrameCreated

FrameCreated is raised when a new iframe is created. Handle this event to get access to CoreWebView2Frame objects.

FrameNavigationCompleted

FrameNavigationCompleted is raised when a child frame has completely loaded (body.onload has been raised) or loading stopped with error.

FrameNavigationStarting

FrameNavigationStarting is raised when a child frame in the WebView requests permission to navigate to a different URI.

HistoryChanged

HistoryChanged is raised for changes to joint session history, which consists of top-level and manual frame navigations.

IsDefaultDownloadDialogOpenChanged

Raised when the IsDefaultDownloadDialogOpen property changes.

IsDocumentPlayingAudioChanged

IsDocumentPlayingAudioChanged is raised when document starts or stops playing audio.

IsMutedChanged

IsMutedChanged is raised when the mute state changes.

LaunchingExternalUriScheme

LaunchingExternalUriScheme is raised when a navigation request is made to a URI scheme that is registered with the OS.

NavigationCompleted

NavigationCompleted is raised when the WebView has completely loaded (body.onload has been raised) or loading stopped with error.

NavigationStarting

NavigationStarting is raised when the WebView main frame is requesting permission to navigate to a different URI.

NewWindowRequested

NewWindowRequested is raised when content inside the WebView requests to open a new window, such as through window.open().

NotificationReceived

Add an event handler for the NotificationReceived event for non-persistent notifications.

        If a deferral is not taken on the event args, the subsequent scripts after
        the DOM notification creation call (i.e. `Notification()`) are blocked
        until the event handler returns. If a deferral is taken, the scripts are
        blocked until the deferral is completed.
PermissionRequested

PermissionRequested is raised when content in a WebView requests permission to access some privileged resources.

ProcessFailed

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.

SaveAsUIShowing
SaveFileSecurityCheckStarting

This event will be raised during system FileTypePolicy checking the dangerous file extension list.

        Developers can specify their own logic for determining whether
        to allow a particular type of file to be saved from the document origin URI.
        Developers can also determine the save decision based on other criteria.

        Here are two properties in <xref data-throw-if-not-resolved="true" uid="Microsoft.Web.WebView2.Core.CoreWebView2SaveFileSecurityCheckStartingEventArgs"></xref> to manage the decision, <xref data-throw-if-not-resolved="true" uid="Microsoft.Web.WebView2.Core.CoreWebView2SaveFileSecurityCheckStartingEventArgs.CancelSave"></xref> and <xref data-throw-if-not-resolved="true" uid="Microsoft.Web.WebView2.Core.CoreWebView2SaveFileSecurityCheckStartingEventArgs.SuppressDefaultPolicy"></xref>.
        Table of Properties' value and result:
        <table><thead><tr><th></th><th>CancelSave</th><th>SuppressDefaultPolicy</th><th>Result</th></tr></thead><tbody><tr><td></td><td>False</td><td>False</td><td>Perform the default policy check. It may show the security warning UI if the file extension is dangerous.</td></tr><tr><td></td><td>False</td><td>True</td><td>Skip the default policy check and the possible security warning. Start saving or downloading.</td></tr><tr><td></td><td>True</td><td>Any</td><td>Skip the default policy check and the possible security warning. Abort save or download.</td></tr></tbody></table>
ScreenCaptureStarting

ScreenCaptureStarting event is raised when the Screen Capture API is requested by the user using getDisplayMedia().

ScriptDialogOpening

ScriptDialogOpening is raised when a JavaScript dialog (alert, confirm, prompt, or beforeunload) displays for the WebView.

ServerCertificateErrorDetected

The ServerCertificateErrorDetected event is raised when the WebView2 cannot verify server's digital certificate while loading a web page.

SourceChanged

SourceChanged is raised when the Source property changes.

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.

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.

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

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

WindowCloseRequested

WindowCloseRequested is raised when content inside the WebView requested to close the window, such as after window.close() is run.

Applies to