Class CoreWebView2Environment
This represents the WebView2 Environment.
public class CoreWebView2Environment
- Inheritance
-
CoreWebView2Environment
- Inherited Members
Remarks
WebViews created from an environment run on the Browser process specified with environment parameters and objects created from an environment should be used in the same environment. Using it in different environments are not guaranteed to be compatible and may fail.
Properties
BrowserVersionString
Gets the browser version info of the current CoreWebView2Environment, including channel name if it is not the stable channel.
public string BrowserVersionString { get; }
Property Value
Remarks
It matches the format of the GetAvailableBrowserVersionString(string) method. Channel names are beta
, dev
, and canary
.
FailureReportFolderPath
Gets the failure report folder that all CoreWebView2s created from this environment are using.
public string FailureReportFolderPath { get; }
Property Value
UserDataFolder
Gets the user data folder that all CoreWebView2s created from this environment are using.
public string UserDataFolder { get; }
Property Value
Remarks
This could be either the value passed in by the developer when creating the environment object or the calculated one for default handling. And will always be an absolute path.
Methods
CompareBrowserVersions(string, string)
Compares two instances of browser versions correctly and returns an integer that indicates whether the first instance is older, the same as, or newer than the second instance.
public static int CompareBrowserVersions(string version1, string version2)
Parameters
version1
stringOne of the version strings to compare.
version2
stringThe other version string to compare.
Returns
- int
An integer that indicates whether the first instance is older, the same as, or newer than the second instance.
Value Type Condition Less than zero version1
is older thanversion2
.Zero version1
is the same asversion2
.Greater than zero version1
is newer thanversion2
.
CreateAsync(string, string, CoreWebView2EnvironmentOptions)
Creates a WebView2 Environment using the installed or a custom WebView2 Runtime version.
public static Task<CoreWebView2Environment> CreateAsync(string browserExecutableFolder = null, string userDataFolder = null, CoreWebView2EnvironmentOptions options = null)
Parameters
browserExecutableFolder
stringThe relative path to the folder that contains a custom version of WebView2 Runtime.
To use a fixed version of the WebView2 Runtime, pass the folder path that contains the fixed version of the WebView2 Runtime to
browserExecutableFolder
. BrowserExecutableFolder supports both relative (to the application's executable) and absolute file paths. To create WebView2 controls that use the installed version of the WebView2 Runtime that exists on user machines, pass anull
or empty string tobrowserExecutableFolder
. In this scenario, the API tries to find a compatible version of the WebView2 Runtime that is installed on the user machine (first at the machine level, and then per user) using the selected channel preference. The path of fixed version of the WebView2 Runtime should not contain \Edge\Application\. When such a path is used, the API fails withERROR_NOT_SUPPORTED
.userDataFolder
stringThe user data folder location for WebView2.
The path is either an absolute file path or a relative file path that is interpreted as relative to the compiled code for the current process. The default user data folder {Executable File Name}.WebView2 is created in the same directory next to the compiled code for the app. WebView2 creation fails if the compiled code is running in a directory in which the process does not have permission to create a new directory. The app is responsible to clean up the associated user data folder when it is done.
options
CoreWebView2EnvironmentOptionsOptions used to create WebView2 Environment.
As a browser process may be shared among WebViews, WebView creation fails if the specified
options
does not match the options of the WebViews that are currently running in the shared browser process.
Returns
Remarks
The default channel search order is the WebView2 Runtime, Beta, Dev, and
Canary. When an override WEBVIEW2_RELEASE_CHANNEL_PREFERENCE
environment
variable or applicable releaseChannelPreference
registry value is set to
1
, the channel search order is reversed.
To use a fixed version of the WebView2 Runtime, pass the relative
folder path that contains the fixed version of the WebView2 Runtime
to browserExecutableFolder
. To create WebView2 controls that
use the installed version of the WebView2 Runtime that exists on
user machines, pass a null
or empty string to
browserExecutableFolder
. In this scenario, the API tries to
find a compatible version of the WebView2 Runtime that is installed
on the user machine (first at the machine level, and then per user)
using the selected channel preference. The path of fixed version of
the WebView2 Runtime should not contain \Edge\Application\. When
such a path is used, the API fails with the following error.
The browserExecutableFolder
, userDataFolder
, and options
may be
overridden by values either specified in environment variables or in
the registry.
When creating a CoreWebView2Environment the following environment variables are verified.
WEBVIEW2_BROWSER_EXECUTABLE_FOLDER
WEBVIEW2_USER_DATA_FOLDER
WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS
WEBVIEW2_RELEASE_CHANNEL_PREFERENCE
If browser executable folder or user data folder is specified in an
environment variable or in the registry, the specified browserExecutableFolder
or userDataFolder
values are overridden. If additional browser
arguments are specified in an environment variable or in the
registry, it is appended to the corresponding value in the specified
options
.
While not strictly overrides, additional environment variables may be set.
Value | Description |
---|---|
WEBVIEW2_WAIT_FOR_SCRIPT_DEBUGGER |
When found with a non-empty value, this indicates that the WebView
is being launched under a script debugger. In this case, the WebView
issues a Page.waitForDebugger CDP command that runs the
script inside the WebView to pause on launch, until a debugger
issues a corresponding Runtime.runIfWaitingForDebugger CDP
command to resume the runtime.
Note that this environment variable does not have a registry key equivalent.
|
WEBVIEW2_PIPE_FOR_SCRIPT_DEBUGGER |
When found with a non-empty value, it indicates that the WebView is
being launched under a script debugger that also supports host apps
that use multiple WebViews. The value is used as the identifier for
a named pipe that is opened and written to when a new WebView is
created by the host app. The payload should match the payload of the
remote-debugging-port JSON target and an external debugger
may use it to attach to a specific WebView instance. The format of
the pipe created by the debugger should be
\\.\pipe\WebView2\Debugger\{app_name}\{pipe_name} , where the
following are true.
To enable debugging of the targets identified by the JSON, you must
set the
If both |
If none of those environment variables exist, then the registry is examined next.
[{Root}]\Software\Policies\Microsoft\Edge\WebView2\BrowserExecutableFolder "{AppId}"=""
[{Root}]\Software\Policies\Microsoft\Edge\WebView2\ReleaseChannelPreference "{AppId}"=""
[{Root}]\Software\Policies\Microsoft\Edge\WebView2\AdditionalBrowserArguments "{AppId}"=""
[{Root}]\Software\Policies\Microsoft\Edge\WebView2\UserDataFolder "{AppId}"=""
Use a group policy under Administrative Templates > Microsoft Edge WebView2 to configure browser executable folder and release channel preference.
Value | Description |
---|---|
ERROR_DISK_FULL | In the unlikely scenario where some instances of WebView are open during a browser update, the deletion of the previous WebView2 Runtime may be blocked. To avoid running out of disk space, a new WebView creation fails with this error if it detects that too many previous WebView2 Runtime versions exist. |
COREWEBVIEW2_MAX_INSTANCES |
The default maximum number of WebView2 Runtime versions allowed is 20 .
To override the maximum number of the previous WebView2 Runtime versions
allowed, set the value of the following environment variable.
|
ERROR_PRODUCT_UNINSTALLED | If the Webview depends upon an installed WebView2 Runtime version and it is uninstalled, any subsequent creation fails with this error. |
First verify with Root as HKLM
and then HKCU
. AppId
is first set to
the Application User Model ID of the process, then if no corresponding
registry key, the AppId
is set to the compiled code name of the process,
or if that is not a registry key then *
. If an override registry key is
found, use the browserExecutableFolder
and userDataFolder
registry
values as replacements and append additionalBrowserArguments
registry
values for the corresponding values in the provided options
.
CreateContextMenuItem(string, Stream, CoreWebView2ContextMenuItemKind)
Create a custom CoreWebView2ContextMenuItem object to insert into the WebView context menu.
public CoreWebView2ContextMenuItem CreateContextMenuItem(string Label, Stream iconStream, CoreWebView2ContextMenuItemKind Kind)
Parameters
Label
stringiconStream
StreamKind
CoreWebView2ContextMenuItemKind
Returns
Remarks
CoreWebView2 will rewind the icon
stream before decoding.
There is a limit of 1000 active custom context menu items at a given time per CoreWebView2Environment. Attempting to create more before deleting existing ones will fail with ERROR_NOT_ENOUGH_QUOTA
. It is recommended to reuse custom ContextMenuItems across CoreWebView2ContextMenuRequested events for performance. The created object's IsEnabled property will default to true
and IsChecked property will default to false
. A CommandId will be assigned that's unique across active custom context menu items, but command ID values of deleted custom ContextMenuItems can be reassigned.
CreateCoreWebView2CompositionControllerAsync(nint)
Asynchronously creates a new WebView for use with visual hosting.
public Task<CoreWebView2CompositionController> CreateCoreWebView2CompositionControllerAsync(nint ParentWindow)
Parameters
ParentWindow
nintThe HWND in which the app will connect the visual tree of the WebView.
Returns
Remarks
ParentWindow
will be the HWND that the app will receive pointer/mouse input meant for the WebView (and will need to use SendMouseInput(CoreWebView2MouseEventKind, CoreWebView2MouseEventVirtualKeys, uint, Point) or SendPointerInput(CoreWebView2PointerEventKind, CoreWebView2PointerInfo) to forward). If the app moves the WebView visual tree to underneath a different window, then it needs to set ParentWindow to update the new parent HWND of the visual tree.
Set RootVisualTarget property on the created CoreWebView2CompositionController to provide a visual to host the browser's visual tree.
It is recommended that the application set Application User Model ID for the process or the application window. If none is set, during WebView creation a generated Application User Model ID is set to root window of ParentWindow
.
It can also accept a CoreWebView2ControllerOptions which is created by CreateCoreWebView2ControllerOptions() as the second parameter for multiple profiles support.
CreateCoreWebView2CompositionController is supported in the following versions of Windows:
- Windows 11
- Windows 10
- Windows Server 2019
- Windows Server 2016
CreateCoreWebView2CompositionControllerAsync(nint, CoreWebView2ControllerOptions)
Asynchronously creates a new CoreWebView2CompositionController object.
public Task<CoreWebView2CompositionController> CreateCoreWebView2CompositionControllerAsync(nint ParentWindow, CoreWebView2ControllerOptions options)
Parameters
ParentWindow
nintThe HWND in which the WebView should be displayed and from which receive input.
options
CoreWebView2ControllerOptionsThe options contains profileName and inPrivate parameters that could be used to create CoreWebView2Profile, and it can be used to create multiple WebViews with multiple profiles under a single user data directory.
Returns
Remarks
Multiple profiles under single user data directory can share some system resources including memory, CPU footprint, disk space (such as compiled shaders and safebrowsing data) etc.
CreateCoreWebView2ControllerAsync(nint)
Asynchronously creates a new WebView.
public Task<CoreWebView2Controller> CreateCoreWebView2ControllerAsync(nint ParentWindow)
Parameters
ParentWindow
nintThe HWND in which the WebView should be displayed and from which receive input.
Returns
Remarks
The WebView adds a child window to the provided window during WebView creation. Z-order and other things impacted by sibling window order are affected accordingly.
HWND_MESSAGE is a valid parameter for ParentWindow
for an invisible WebView for Windows 8 and above. In this case the window will never become visible. You are not able to reparent the window after you have created the WebView. This is not supported in Windows 7 or below. Passing this parameter in Windows 7 or below will return ERROR_INVALID_WINDOW_HANDLE in the controller callback.
It can also accept a CoreWebView2ControllerOptions which is created by CreateCoreWebView2ControllerOptions() as the second parameter for multiple profiles support. As WebView2 is built on top of Edge browser, it follows Edge's behavior pattern. To create an InPrivate WebView, we gets an off-the-record profile (an InPrivate profile) from a regular profile, then create the WebView with the off-the-record profile. Multiple profiles under single user data directory can share some system resources including memory, CPU footprint, disk space (such as compiled shaders and safebrowsing data) etc.
It is recommended that the application set Application User Model ID for the process or the application window. If none is set, during WebView creation a generated Application User Model ID is set to root window of ParentWindow
.
It is recommended that the app handles restart manager messages, to gracefully restart it in the case when the app is using the WebView2 Runtime from a certain installation and that installation is being uninstalled. For example, if a user installs a version of the WebView2 Runtime and opts to use another version of the WebView2 Runtime for testing the app, and then uninstalls the 1st version of the WebView2 Runtime without closing the app, the app restarts to allow un-installation to succeed.
When the app retries CreateCoreWebView2ControllerAsync upon failure, it is recommended that the app restarts from creating a new WebView2 Environment. If a WebView2 Runtime update happens, the version associated with a WebView2 Environment may have been removed and causing the object to no longer work. Creating a new WebView2 Environment works since it uses the latest version.
WebView creation fails if a running instance using the same user data folder exists, and the Environment objects have different CoreWebView2EnvironmentOptions. For example, if a WebView was created with one Language, an attempt to create a WebView with a different Language using the same user data folder fails.
WebView creation can fail with `E_UNEXPECTED` if runtime does not have permissions to the user data folder.
CreateCoreWebView2ControllerAsync(nint, CoreWebView2ControllerOptions)
Asynchronously creates a new CoreWebView2Controller object.
public Task<CoreWebView2Controller> CreateCoreWebView2ControllerAsync(nint ParentWindow, CoreWebView2ControllerOptions options)
Parameters
ParentWindow
nintThe HWND in which the WebView should be displayed and from which receive input.
options
CoreWebView2ControllerOptionsThe options contains profileName and inPrivate parameters that could be used to create CoreWebView2Profile, and it can be used to create multiple WebViews with multiple profiles under a single user data directory.
Returns
Remarks
Multiple profiles under single user data directory can share some system resources including memory, CPU footprint, disk space (such as compiled shaders and safebrowsing data) etc.
CreateCoreWebView2ControllerOptions()
Creates a new CoreWebView2ControllerOptions object, which can be passed as a parameter in CreateCoreWebView2ControllerAsync(nint, CoreWebView2ControllerOptions) and CreateCoreWebView2CompositionControllerAsync(nint, CoreWebView2ControllerOptions) function for multiple profiles support.
public CoreWebView2ControllerOptions CreateCoreWebView2ControllerOptions()
Returns
- CoreWebView2ControllerOptions
A CoreWebView2ControllerOptions that can be passed when calling CreateCoreWebView2ControllerAsync(nint, CoreWebView2ControllerOptions) and CreateCoreWebView2CompositionControllerAsync(nint, CoreWebView2ControllerOptions).
Remarks
The options is a settable property while the default for profile name is an empty string and the default value for IsInPrivateModeEnabled is false. The profile will be created on disk or opened when calling CreateCoreWebView2ControllerWithOptions no matter InPrivate mode is enabled or not, and it will be released in memory when the correspoding CoreWebView2Controller is closed but still remain on disk. As WebView2 is built on top of Edge browser, it follows Edge's behavior pattern. To create an InPrivate WebView, we get an off-the-record profile (an InPrivate profile) from a regular profile, then create the WebView with the off-the-record profile. Also the profile name can be reused.
CreateCoreWebView2PointerInfo()
Creates an empty CoreWebView2PointerInfo.
public CoreWebView2PointerInfo CreateCoreWebView2PointerInfo()
Returns
Remarks
The returned CoreWebView2PointerInfo needs to be populated with all of the relevant info before calling SendPointerInput(CoreWebView2PointerEventKind, CoreWebView2PointerInfo).
CreatePrintSettings()
Creates the CoreWebView2PrintSettings used by the PrintToPdfAsync(string, CoreWebView2PrintSettings) method.
public CoreWebView2PrintSettings CreatePrintSettings()
Returns
CreateSharedBuffer(ulong)
Create a shared memory based buffer with the specified size in bytes.
public CoreWebView2SharedBuffer CreateSharedBuffer(ulong Size)
Parameters
Size
ulong
Returns
Remarks
The buffer can be shared with web contents in WebView by calling PostSharedBufferToScript(CoreWebView2SharedBuffer, CoreWebView2SharedBufferAccess, string) or PostSharedBufferToScript(CoreWebView2SharedBuffer, CoreWebView2SharedBufferAccess, string). Once shared, the same content of the buffer will be accessible from both the app process and script in WebView. Modification to the content will be visible to all parties that have access to the buffer. The shared buffer is presented to the script as ArrayBuffer. All JavaScript APIs that work for ArrayBuffer including Atomics APIs can be used on it. There is currently a limitation that only size less than 2GB is supported.
CreateWebResourceRequest(string, string, Stream, string)
Creates a new CoreWebView2WebResourceRequest object.
public CoreWebView2WebResourceRequest CreateWebResourceRequest(string uri, string Method, Stream postData, string Headers)
Parameters
uri
stringThe request URI.
Method
stringThe HTTP request method.
postData
StreamHeaders
stringThe raw request header string delimited by CRLF (optional in last header).
Returns
Remarks
uri
parameter must be absolute URI. It's also possible to create this object with null
headers string and then use the CoreWebView2HttpRequestHeaders to construct the headers line by line.
- See Also
CreateWebResourceResponse(Stream, int, string, string)
Creates a new CoreWebView2WebResourceResponse object.
public CoreWebView2WebResourceResponse CreateWebResourceResponse(Stream Content, int StatusCode, string ReasonPhrase, string Headers)
Parameters
Content
StreamHTTP response content as stream.
StatusCode
intThe HTTP response status code.
ReasonPhrase
stringThe HTTP response reason phrase.
Headers
stringThe raw response header string delimited by newline.
Returns
Remarks
It is also possible to create this object with empty headers string and then use the CoreWebView2HttpResponseHeaders to construct the headers line by line.
- See Also
GetAvailableBrowserVersionString(string)
Gets the browser version info including channel name if it is not the stable channel or WebView2 Runtime.
public static string GetAvailableBrowserVersionString(string browserExecutableFolder)
Parameters
browserExecutableFolder
stringThe relative path to the folder that contains the WebView2 Runtime.
Returns
Exceptions
- WebView2RuntimeNotFoundException
WebView2 Runtime installation is missing.
GetAvailableBrowserVersionString(string, CoreWebView2EnvironmentOptions)
Gets the browser version info including channel name if it is not the stable channel or WebView2 Runtime.
public static string GetAvailableBrowserVersionString(string browserExecutableFolder = null, CoreWebView2EnvironmentOptions environmentOptions = null)
Parameters
browserExecutableFolder
stringThe relative path to the folder that contains the WebView2 Runtime.
environmentOptions
CoreWebView2EnvironmentOptionsThe environment options used to create the environment.
Returns
Exceptions
- WebView2RuntimeNotFoundException
WebView2 Runtime installation is missing.
GetProcessExtendedInfosAsync()
Returns a snapshot collection of CoreWebView2ProcessInfo corresponding to all currently running processes associated with this CoreWebView2Environment excludes crashpad process. This provides the same list of CoreWebView2ProcessInfo as what's provided in GetProcessInfos(), but additionally provides a list of associated CoreWebView2FrameInfo which are actively running (showing or hiding UI elements) in the renderer process. See AssociatedFrameInfos for more information.
public Task<IReadOnlyList<CoreWebView2ProcessExtendedInfo>> GetProcessExtendedInfosAsync()
Returns
Examples
GetProcessInfos()
Returns the list of all CoreWebView2ProcessInfo using same user data folder except for crashpad process.
public IReadOnlyList<CoreWebView2ProcessInfo> GetProcessInfos()
Returns
Examples
SetLoaderDllFolderPath(string)
Set the path of the folder containing the WebView2Loader.dll
.
public static void SetLoaderDllFolderPath(string folderPath)
Parameters
folderPath
stringThe path of the folder containing the
WebView2Loader.dll
.
Remarks
This function allows you to set the path of the folder containing the WebView2Loader.dll
. This should be the path of a folder containing WebView2Loader.dll
and not a path to the WebView2Loader.dll
file itself.
Note that the WebView2 SDK contains multiple WebView2Loader.dll
files for different CPU architectures. When specifying folder path, you must specify one containing a WebView2Loader.dll
module with a CPU architecture matching the current process CPU architecture.
This function is used to load the WebView2Loader.dll
module during calls to any other static methods on CoreWebView2Environment
. So, the path should be specified before any other API is called in CoreWebView2Environment
class. Once WebView2Loader.dll
is successfully loaded this function will throw an InvalidOperationException exception.
The path can be relative or absolute. Relative paths are relative to the path of the Microsoft.Web.WebView2.Core.dll
module.
If the WebView2Loader.dll
file does not exist in that path or LoadLibrary cannot load the file, or LoadLibrary fails for any other reason, an exception corresponding to the LoadLibrary failure is thrown when any other API is called in CoreWebView2Environment
class. For instance, if the file cannot be found a DllNotFoundException
exception will be thrown.
Exceptions
- InvalidOperationException
Thrown when
WebView2Loader.dll
has been successfully loaded.
Events
BrowserProcessExited
BrowserProcessExited is raised when the collection of WebView2 Runtime processes for the browser process of this CoreWebView2Environment terminate due to browser process failure or normal shutdown (for example, when all associated WebViews are closed), after all resources have been released (including the user data folder).
public event EventHandler<CoreWebView2BrowserProcessExitedEventArgs> BrowserProcessExited
Event Type
Examples
Remarks
Multiple app processes can share a browser process by creating their webviews from a CoreWebView2Environment with the same user data folder. When the entire collection of WebView2Runtime processes for the browser process exit, all associated CoreWebView2Environment objects receive the BrowserProcessExited event. Multiple processes sharing the same browser process need to coordinate their use of the shared user data folder to avoid race conditions and unnecessary waits. For example, one process should not clear the user data folder at the same time that another process recovers from a crash by recreating its WebView controls; one process should not block waiting for the event if other app processes are using the same browser process (the browser process will not exit until those other processes have closed their webviews too).
Note this is an event from CoreWebView2Environment, not CoreWebView2. The difference between BrowserProcessExited and ProcessFailed is that BrowserProcessExited is raised for any browser process exit (expected or unexpected, after all associated processes have exited too), while ProcessFailed is raised for unexpected process exits of any kind (browser, render, GPU, and all other types), or for main frame render process unresponsiveness. To learn more about the WebView2 Process Model, go to Process model.
In the case the browser process crashes, both BrowserProcessExited and ProcessFailed events are raised, but the order is not guaranteed. These events are intended for different scenarios. It is up to the app to coordinate the handlers so they do not try to perform reliability recovery while also trying to move to a new WebView2 Runtime version or remove the user data folder.
NewBrowserVersionAvailable
NewBrowserVersionAvailable is raised when a newer version of the WebView2 Runtime is installed and available using WebView2.
public event EventHandler<object> NewBrowserVersionAvailable
Event Type
Examples
Remarks
To use the newer version of the browser you must create a new environment and WebView. The event is only raised for new version from the same WebView2 Runtime from which the code is running. When not running with installed WebView2 Runtime, no event is raised.
Because a user data folder is only able to be used by one browser process at a time, if you want to use the same user data folder in the WebViews using the new version of the browser, you must close the environment and instance of WebView that are using the older version of the browser first. Or simply prompt the user to restart the app.
ProcessInfosChanged
ProcessInfosChanged is raised when a collection of WebView2 Runtime processes changed due to new process being detected or when a existing process gone away.
public event EventHandler<object> ProcessInfosChanged