cWebView2Host Events Reference
📋 Events Overview
cWebView2Host provides 40+ events covering the entire WebView2 lifecycle. To use events, declare the variable with WithEvents:
Dim WithEvents wv As cWebView2HostEvent Category Index
| Category | Event | Trigger Timing |
|---|---|---|
| Lifecycle | Create | WebView2 control creation completed |
| Ready | First navigation completed, control ready | |
| Error | Error during creation or runtime | |
| Navigation | NavigationStarting | Navigation starting (cancelable) |
| NavigationComplete | Navigation completed | |
| SourceChanged | URL changed | |
| DocumentTitleChanged | Document title changed | |
| DOMContentLoaded | DOM loading completed | |
| Permission/Dialog | PermissionRequested | Page requests permission |
| ScriptDialogOpening | Script dialog appearing (alert/confirm/prompt) | |
| AcceleratorKeyPressed | Accelerator key pressed | |
| NewWindowRequested | Page requests opening new window | |
| Resources | WebResourceRequested | Web resource request intercepted |
| ProcessFailed | Browser process failed | |
| DownloadStarting | Download about to start | |
| Scripting | JsAsyncResult | Async script execution completed |
| JsMessage | JS postMessage received | |
| DevToolsProtocolResponse | CDP async response | |
| Host Mouse | HostMouseDown | Mouse down in host area |
| HostMouseUp | Mouse up in host area | |
| HostMouseDblClick | Mouse double-click in host area | |
| HostMouseMove | Mouse move in host area | |
| HostMouseWheel | Mouse wheel in host area | |
| HostContextMenu | Context menu in host area | |
| Host Keyboard | HostKeyDown | Key down in host area |
| HostKeyUp | Key up in host area | |
| HostKeyPress | Key press in host area | |
| HostFocus | WebView2 gained focus | |
| HostBlur | WebView2 lost focus | |
| HostResize | Host window size changed | |
| User Mouse | UserMouseDown | Mouse down in content area |
| UserMouseUp | Mouse up in content area | |
| UserMouseMove | Mouse move in content area | |
| UserMouseWheel | Mouse wheel in content area | |
| UserContextMenu | Context menu in content area | |
| UserDblClick | Mouse double-click in content area | |
| Suspend | SuspendCompleted | Suspend succeeded |
| SuspendFailed | Suspend failed | |
| PrintToPdfCompleted | PDF print succeeded | |
| PrintToPdfFailed | PDF print failed | |
| Business | OnGetCookiesFull | Async cookie retrieval completed |
🔄 Lifecycle Events
Create
WebView2 control creation completed, but navigation has not yet started.
Private Sub wv_Create()Trigger Timing: After WebView2 Environment and Controller are successfully created.
Purpose: This is the correct timing to configure EnvironmentOptions and Security, since the environment is created but navigation has not yet started.
Example:
Private Sub wv_Create()
' Configure user data directory
wv.EnvironmentOptions.UserDataFolder = App.Path & "\UserDir\account-001"
' Configure security options
wv.Security.CertificateErrorAction = CEA_AlwaysAllow
End SubReady
WebView2 first navigation completed, control fully ready.
Private Sub wv_Ready()Trigger Timing: Fires once after the first navigation completes. Subsequent navigations do not trigger this event.
Purpose: Safely perform initialization operations such as binding events, registering data bindings, injecting scripts, etc.
Example:
Private Sub wv_Ready()
Me.Caption = wv.DocumentTitle
' Set up data bindings
wv.BindData "name", "#name-input", "value"
wv.BindUI Me, "OnNameInput", "#name-input", EventName:="input"
wv.SetData "name", "Default value"
' Inject script
wv.AddScriptToExecuteOnDocumentCreated "window.__appReady = true;"
End SubError
Error during creation or runtime.
Private Sub wv_Error(ByVal Description As String)Parameters:
Description- Error description message
🧭 Navigation Events
NavigationStarting
Navigation is about to start — can be canceled via the Cancel parameter.
Private Sub wv_NavigationStarting(ByVal Uri As String, ByVal IsUserInitiated As Boolean, ByRef Cancel As Boolean)Parameters:
Uri- Target URLIsUserInitiated- Whether triggered by user action (e.g., clicking a link)Cancel- Set to True to cancel navigation
Example:
Private Sub wv_NavigationStarting(ByVal Uri As String, ByVal IsUserInitiated As Boolean, ByRef Cancel As Boolean)
' Block navigation to specific domain
If InStr(UCase(Uri), "ADS.EXAMPLE.COM") > 0 Then
Cancel = True
End If
End SubNavigationComplete
Navigation completed.
Private Sub wv_NavigationComplete(ByVal IsSuccess As Boolean, ByVal ErrorStatus As wv2ErrorStatus)Parameters:
IsSuccess- Whether navigation succeededErrorStatus- Error status code (0 on success)
SourceChanged
URL changed.
Private Sub wv_SourceChanged(ByVal IsNewDocument As Boolean)Parameters:
IsNewDocument- Whether this is a new document (vs. same-page navigation)
DocumentTitleChanged
Document title changed.
Private Sub wv_DocumentTitleChanged()Example:
Private Sub wv_DocumentTitleChanged()
Me.Caption = wv.DocumentTitle
End SubDOMContentLoaded
DOM content loading completed (earlier than NavigationComplete).
Private Sub wv_DOMContentLoaded()Purpose: Perform operations when DOM is ready but resources (images, etc.) have not fully loaded.
🔐 Permission/Dialog Events
PermissionRequested
Page requests permission (geolocation, camera, microphone, etc.).
Private Sub wv_PermissionRequested(ByVal Uri As String, ByVal PermissionKind As wv2PermissionKind, ByVal IsUserInitiated As Boolean, ByRef State As wv2PermissionState)Parameters:
Uri- URL of the page requesting permissionPermissionKind- Permission type enumIsUserInitiated- Whether triggered by user actionState- Permission state, can be set towv2PermissionState_Alloworwv2PermissionState_Deny
Example:
Private Sub wv_PermissionRequested(ByVal Uri As String, ByVal PermissionKind As wv2PermissionKind, ByVal IsUserInitiated As Boolean, ByRef State As wv2PermissionState)
' Auto-allow geolocation from trusted domains
If PermissionKind = wv2PermissionKind_Geolocation And InStr(Uri, "myapp.com") > 0 Then
State = wv2PermissionState_Allow
Else
State = wv2PermissionState_Deny
End If
End SubScriptDialogOpening
JavaScript dialog about to appear (alert / confirm / prompt / beforeunload).
Private Sub wv_ScriptDialogOpening(ByVal Kind As wv2ScriptDialogKind, ByVal Message As String, ByRef Accept As Boolean)Parameters:
Kind- Dialog typeMessage- Dialog message contentAccept- Set to True to accept the dialog (equivalent to clicking OK), False to cancel
Note: Can be used to customize dialog appearance, replacing the browser's default dialogs.
AcceleratorKeyPressed
Accelerator key pressed event.
Private Sub wv_AcceleratorKeyPressed(ByVal KeyEventKind As wv2KeyEventKind, ByVal VirtualKey As Long, ByRef Handled As Boolean)Parameters:
KeyEventKind- Key event type (KeyDown/Up/SystemKeyDown/Up)VirtualKey- Virtual key codeHandled- Set to True to prevent WebView2 from handling this key
Example:
Private Sub wv_AcceleratorKeyPressed(ByVal KeyEventKind As wv2KeyEventKind, ByVal VirtualKey As Long, ByRef Handled As Boolean)
' Intercept F5 refresh
If VirtualKey = vbKeyF5 Then
Handled = True
' Custom refresh logic
End If
End SubNewWindowRequested
Page requests opening a new window (target="_blank" or window.open).
Private Sub wv_NewWindowRequested(ByVal Uri As String, ByVal IsUserInitiated As Boolean, ByRef Handled As Boolean)Parameters:
Uri- Target URL of the new windowIsUserInitiated- Whether triggered by user actionHandled- Set to True to prevent opening a new window
Example:
Private Sub wv_NewWindowRequested(ByVal Uri As String, ByVal IsUserInitiated As Boolean, ByRef Handled As Boolean)
' Navigate in current window (block popup)
Handled = True
wv.Navigate Uri
End Sub📦 Resource Events
WebResourceRequested
Web resource request intercepted by AddWebResourceRequestedFilter.
Private Sub wv_WebResourceRequested(ByVal Request As WebView2Request, ByVal Response As WebView2Response)Parameters:
Request- Request object, can read Method, Uri, Headers, ContentResponse- Response object; after setting values, WebView2 uses this response instead of the actual network request
Note: Must call AddWebResourceRequestedFilter to register a filter before this event will fire.
ProcessFailed
Browser process failed.
Private Sub wv_ProcessFailed(ByVal FailedKind As wv2ProcessFailedKind)Parameters:
FailedKind- Process failure type enum
DownloadStarting
Download about to start.
Private Sub wv_DownloadStarting(ByVal ResultFilePath As String, ByRef Cancel As Boolean, ByRef Handled As Boolean)Parameters:
ResultFilePath- Download file pathCancel- Set to True to cancel downloadHandled- Set to True to indicate handled
⚡ Script Events
JsAsyncResult
Async script execution completed (callback for ExecuteScript / JsRunAsync).
Private Sub wv_JsAsyncResult(ByVal Token As Long, ByVal Result As String, ByVal ErrorCode As Long)Parameters:
Token- Token specified at call timeResult- JSON string of JS execution resultErrorCode- Error code, 0 indicates success
Example:
wv.ExecuteScript "document.title", 1001
wv.JsRunAsync "fetch('/api').then(r=>r.json())" ' Returns auto token
Private Sub wv_JsAsyncResult(ByVal Token As Long, ByVal Result As String, ByVal ErrorCode As Long)
If ErrorCode = 0 Then
Debug.Print "Token " & Token & " => " & Result
End If
End SubJsMessage
Message received from JS via window.chrome.webview.postMessage().
Private Sub wv_JsMessage(ByVal Message As String)Parameters:
Message- Message string sent from JS
Example:
' VB6 side
Private Sub wv_JsMessage(ByVal Message As String)
Debug.Print "JS message: " & Message
End Sub
' JS side
window.chrome.webview.postMessage("Hello from JS");DevToolsProtocolResponse
CDP async call response.
Private Sub wv_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String)Parameters:
CustomEventId- Custom event ID specified at call timeJsonResponse- JSON string of CDP response
Example:
wv.CallDevToolsProtocolMethod "Page.captureScreenshot", "{}", "screenshot"
Private Sub wv_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String)
If CustomEventId = "screenshot" Then
' Process screenshot data
End If
End Sub🖱️ Host Mouse Events
Host mouse events are captured by subclassing the host window and reflect mouse operations in the host window area (not the WebView2 content area).
HostMouseDown
Private Sub wv_HostMouseDown(ByVal Button As wv2MouseButton, ByVal Shift As wv2ShiftState, ByVal X As Long, ByVal Y As Long)Parameters:
Button- Mouse button (1=Left, 2=Right, 4=Middle, bitmask)Shift- Modifier key state (1=Shift, 2=Ctrl, 4=Alt, bitmask)X,Y- Mouse coordinates (client area pixels)
HostMouseUp
Private Sub wv_HostMouseUp(ByVal Button As wv2MouseButton, ByVal Shift As wv2ShiftState, ByVal X As Long, ByVal Y As Long)HostMouseDblClick
Private Sub wv_HostMouseDblClick(ByVal Button As wv2MouseButton, ByVal Shift As wv2ShiftState, ByVal X As Long, ByVal Y As Long)HostMouseMove
Private Sub wv_HostMouseMove(ByVal Button As wv2MouseButton, ByVal Shift As wv2ShiftState, ByVal X As Long, ByVal Y As Long)Note: Requires EnableMouseMoveEvents = True to fire; disabled by default to avoid performance issues.
HostMouseWheel
Private Sub wv_HostMouseWheel(ByVal Delta As Long, ByVal Shift As wv2ShiftState, ByVal X As Long, ByVal Y As Long)Parameters:
Delta- Wheel delta, positive for scroll up, negative for scroll down
HostContextMenu
Private Sub wv_HostContextMenu(ByVal X As Long, ByVal Y As Long)⌨️ Host Keyboard Events
HostKeyDown / HostKeyUp / HostKeyPress
Private Sub wv_HostKeyDown(ByVal KeyCode As Long, ByVal Shift As wv2ShiftState)
Private Sub wv_HostKeyUp(ByVal KeyCode As Long, ByVal Shift As wv2ShiftState)
Private Sub wv_HostKeyPress(ByVal KeyAscii As Long)HostFocus / HostBlur
Private Sub wv_HostFocus()
Private Sub wv_HostBlur()HostResize
Private Sub wv_HostResize()Note: Fires when host window size changes; can call wv.Resize() here to manually adjust WebView2 size (e.g., when using MessageWindowAdapter).
🎯 User Mouse Events
User mouse events are synchronously called back from the WebView2 content area to the host via the mouseProxy COM proxy. Requires EnableUserMouseEvents = True.
UserMouseDown / UserMouseUp
Private Sub wv_UserMouseDown(ByVal Button As Long, ByVal X As Long, ByVal Y As Long, ByVal Shift As Long, ByRef Handled As Boolean)
Private Sub wv_UserMouseUp(ByVal Button As Long, ByVal X As Long, ByVal Y As Long, ByVal Shift As Long, ByRef Handled As Boolean)Parameters:
Button- Mouse button (1=Left, 2=Right, 4=Middle)X,Y- Pixel coordinates within content areaShift- Modifier key stateHandled- Set to True to prevent event from propagating to WebView2
UserMouseMove
Private Sub wv_UserMouseMove(ByVal X As Long, ByVal Y As Long, ByVal Shift As Long, ByRef Handled As Boolean)Note: Requires additional EnableUserMouseMove = True; disabled by default to avoid performance issues.
UserMouseWheel
Private Sub wv_UserMouseWheel(ByVal Delta As Long, ByVal X As Long, ByVal Y As Long, ByVal Shift As Long, ByRef Handled As Boolean)UserContextMenu
Private Sub wv_UserContextMenu(ByVal X As Long, ByVal Y As Long, ByRef Handled As Boolean)UserDblClick
Private Sub wv_UserDblClick(ByVal Button As Long, ByVal X As Long, ByVal Y As Long, ByVal Shift As Long, ByRef Handled As Boolean)🔌 Suspend/PDF/Business Events
SuspendCompleted / SuspendFailed
Private Sub wv_SuspendCompleted()
Private Sub wv_SuspendFailed(ByVal ErrorCode As Long)PrintToPdfCompleted / PrintToPdfFailed
Private Sub wv_PrintToPdfCompleted(ByVal ResultFilePath As String)
Private Sub wv_PrintToPdfFailed(ByVal ErrorCode As Long)OnGetCookiesFull
Async full cookie retrieval completed.
Private Sub wv_OnGetCookiesFull(ByVal CookiesJson As String)Trigger Timing: When async result returns after calling wv.Cookies.GetCookiesFullAsync().
📐 Enum Reference
wv2MouseButton
| Constant | Value | Description |
|---|---|---|
| Left | 1 | Left mouse button |
| Right | 2 | Right mouse button |
| Middle | 4 | Middle mouse button |
Bitmask combination, can include multiple values simultaneously.
wv2ShiftState
| Constant | Value | Description |
|---|---|---|
| Shift | 1 | Shift key |
| Ctrl | 2 | Ctrl key |
| Alt | 4 | Alt key |
Bitmask combination. Detection method: If Shift And 2 Then ' Ctrl is pressed
wv2ScriptDialogKind
| Constant | Description |
|---|---|
| Alert | alert() dialog |
| Confirm | confirm() dialog |
| Prompt | prompt() dialog |
| BeforeUnload | beforeunload dialog |
wv2PermissionKind
| Constant | Description |
|---|---|
| Unknown | Unknown permission |
| Microphone | Microphone |
| Camera | Camera |
| Geolocation | Geolocation |
| Notifications | Notifications |
| OtherSensors | Other sensors |
| ClipboardRead | Clipboard read |
wv2PermissionState
| Constant | Description |
|---|---|
| Default | Default (browser decides) |
| Allow | Allow |
| Deny | Deny |
EnumCertificateErrorAction
| Constant | Value | Description |
|---|---|---|
| CEA_Default | 0 | Default behavior (deny) |
| CEA_Cancel | 1 | Cancel request |
| CEA_AlwaysAllow | 2 | Always allow (injects command-line argument) |
Last Updated: 2026-06-24