Skip to content

cWebView2Host Property & Method Usage Timing Reference

Different APIs have different availability timings within the WebView2 lifecycle. This document categorizes all properties and methods by earliest available timing, helping developers avoid calling them at incorrect stages where they may fail or have no effect.

Lifecycle Stage Overview

The WebView2 complete lifecycle includes an Initialization Phase and a Runtime Phase, with all events as follows:

Initialization Phase (one-time, sequential)

User calls Initialize()

① Create event ─── Configure EnvironmentOptions / Security (only available in this event)

② Internally creates Environment (reads EnvironmentOptions configuration)

③ Internally creates Controller + CoreWebView (reads Settings configuration)

④ Ready event ─── Control fully ready, all APIs become available

⑤ First Navigate (if InitialURL is specified)

Runtime Phase (triggered per navigation cycle)

Navigate / NavigateCustom / NavigateToString / GoBack / GoForward / Reload

⑥ NavigationStarting ─── Can Cancel to block navigation

⑦ SourceChanged ─── URL change (IsNewDocument indicates new page)
  ↓  ┌─ ContentLoading (internal event, not exposed)

⑧ DOMContentLoaded ─── DOM ready, can BindUI / BindData / execute JS
  ↓  │
⑨ DocumentTitleChanged ─── Title change

⑩ NavigationComplete ─── Page fully loaded (including images and other resources)
     └────────────────────────────────────────┘

Each navigation re-triggers ⑥→⑩

Runtime Phase (interaction events that may fire at any time)

┌─ Permissions/Dialogs ───────────────────────────────┐
│  PermissionRequested    Page requests permission (geo/camera etc.)│
│  ScriptDialogOpening    JS dialogs (alert/confirm) │
│  NewWindowRequested     Page requests new window          │
│  AcceleratorKeyPressed  Shortcut key pressed               │
└──────────────────────────────────────────────────────┘

┌─ Resources/Downloads ───────────────────────────────┐
│  WebResourceRequested  Resource request intercepted (must register first) │
│  DownloadStarting      Download about to start (can Cancel)  │
│  ProcessFailed         Browser process crashed             │
└──────────────────────────────────────────────────────┘

┌─ Script Callbacks ──────────────────────────────────┐
│  JsAsyncResult         Async JS execution complete          │
│  JsMessage             JS postMessage to host     │
│  DevToolsProtocolResponse  CDP async response          │
└──────────────────────────────────────────────────────┘

┌─ Host Interaction ──────────────────────────────────┐
│  HostMouseDown/Up/DblClick/Move/Wheel/ContextMenu│
│  HostKeyDown/Up/Press   Keyboard events                 │
│  HostFocus / HostBlur   Focus in/out                 │
│  HostResize             Host window size change           │
└──────────────────────────────────────────────────────┘

┌─ Content Area Mouse (requires EnableUserMouseEvents=True)────┐
│  UserMouseDown/Up/Move/Wheel/ContextMenu/DblClick│
└──────────────────────────────────────────────────────┘

┌─ Async Operation Callbacks ──────────────────────────┐
│  SuspendCompleted / SuspendFailed                │
│  PrintToPdfCompleted / PrintToPdfFailed          │
│  OnGetCookiesFull                                │
└──────────────────────────────────────────────────────┘

┌─ Errors ─────────────────────────────────────────────┐
│  Error                  Creation/runtime error           │
└──────────────────────────────────────────────────────┘

Stage & API Availability Reference

StageTimingWhat you can do
Before Initialize callObject just createdOnly set EnvironmentOptions sub-properties
Create eventBefore Environment creationSet EnvironmentOptions, Security configuration
Ready eventControl fully readyNavigate, register bindings, inject scripts, set runtime properties
DOMContentLoadedDOM readyBindUI, BindData, execute JS (ensure elements exist)
NavigationCompletePage fully loadedAll runtime APIs unrestricted
Any time at runtimeAfter ReadyAll APIs unrestricted

Property Usage Timing Overview

🔴 Only in Create Event (pre-creation configuration)

These properties affect WebView2 Environment creation parameters and must be set in the wv_Create event. Changes after this have no effect.

PropertySub-propertyDescription
EnvironmentOptionsUserDataFolderUser data directory, read when Environment is created, changes afterwards have no effect
BrowserExecutableFolderBrowser executable folder
AdditionalBrowserArgumentsAdditional command-line arguments (e.g., --ignore-certificate-errors)
LanguageBrowser default language
TargetCompatibleBrowserVersionTarget compatible version
AllowSingleSignOnUsingOSPrimaryAccountSSO configuration
ExclusiveUserDataFolderAccessExclusive data folder
EnableTrackingPreventionTracking prevention
SecurityCertificateErrorActionCertificate error handling policy, must be set before Create

Example:

vb
Private Sub wv_Create()
    ' ★ These can ONLY be set in the Create event!
    wv.EnvironmentOptions.UserDataFolder = App.Path & "\UserDir\account-001"
    wv.EnvironmentOptions.AdditionalBrowserArguments = "--ignore-certificate-errors"
    wv.Security.CertificateErrorAction = CEA_AlwaysAllow
End Sub

🟡 Available from Ready Event (runtime settings)

These properties require the CoreWebView2 Controller/Settings object to be created and can be set from the wv_Ready event onwards. Setting them in the Create event may have no effect (the underlying Settings object has not been created yet).

PropertyDescriptionNote
IsPasswordAutoSaveEnabledPassword auto-saveDefault False, only effective after Ready
IsGeneralAutoFillEnabledForm auto-fillDefault False, only effective after Ready
IsScriptEnabledJS execution toggleDefault True
AreDevToolsEnabledDevTools toggleDefault True, recommended off for production
IsStatusBarEnabledStatus bar displayDefault False
IsZoomControlEnabledUser zoom controlDefault True
AreDefaultContextMenusEnabledRight-click menusDefault True
UserAgentCustom UATakes effect for subsequent requests after setting
IsPinchZoomEnabledPinch zoomDefault True
IsSwipeNavigationEnabledSwipe navigationDefault True
AreBrowserAcceleratorKeysEnabledBrowser shortcut keysDefault True
ZoomFactorZoom factorDefault 1.0, requires page loaded
EnableUserMouseEventsContent area mouse eventsDefault False, set after Ready and auto-injects proxy
EnableUserMouseMoveContent area mousemoveRequires EnableUserMouseEvents to be True
EnableMouseMoveEventsHost mousemoveDefault False

Example:

vb
Private Sub wv_Ready()
    ' ★ Runtime property settings
    wv.IsPasswordAutoSaveEnabled = True
    wv.IsGeneralAutoFillEnabled = True
    wv.AreDevToolsEnabled = False      ' Disable DevTools in production
    wv.UserAgent = "Mozilla/5.0 (MyApp)"
    
    ' Enable mouse event proxy
    wv.EnableUserMouseEvents = True
End Sub

🟢 Available any time (read-only state)

These properties are read-only and can be read at any time, but only have valid values after Ready.

PropertyDescriptionValue before Ready
IsReadyWhether readyFalse → True
hWndChild window handle0 → Valid handle
BrowserProcessIdProcess ID0 → Valid ID
CanGoBackCan go backFalse
CanGoForwardCan go forwardFalse
IsSuspendedWhether suspendedFalse
IsMutedWhether mutedFalse
IsDocumentPlayingAudioPlaying audioFalse
IsDefaultDownloadDialogOpenDownload dialogFalse
DocumentURLCurrent URL"" → Valid URL
DocumentTitleCurrent title"" → Valid title
SupportsWebView2~9Feature detectionAccurate values only after Ready
CookiesCookie objectAvailable after Ready
ScriptScript objectAvailable after Ready
HostAdapterNameAdapter nameHas value at Initialize time

Method Usage Timing Overview

🔴 Only in Create Event

MethodDescription
No methods are currently restricted to only the Create event

Note: Although some methods can be called in the Create event, the underlying CoreWebView object has not been created yet, and most methods will silently fail (protected by If m_Core Is Nothing Then Exit Sub). The sole purpose of the Create event is to configure EnvironmentOptions and Security.

🟡 Available from Ready Event

These methods require the CoreWebView object to be created and can only be called from the wv_Ready event onwards:

MethodDescriptionNote
NavigateNavigate to URLCall after Ready, calling in Create has no effect
NavigateCustomCustom request navigationSame as above
NavigateToStringLoad HTML stringSame as above
GoBack / GoForward / ReloadNavigation controlRequires navigation history
ExecuteScriptAsync execute JSRequires page loaded
JsRunSync call JSRequires page loaded
JsRunAsyncAsync call JSRequires page loaded
JsPropRead JS propertyRequires page loaded
PostWebMessageSend string messageRequires page loaded
PostWebMessageJSONSend JSON messageRequires page loaded
AddObjectInject COM objectInject after Ready, page JS can access
RemoveObjectRemove COM object
AddScriptToExecuteOnDocumentCreatedInject scriptInject after Ready, subsequent pages execute
AddWebResourceRequestedFilterAdd resource filterRegister after Ready to take effect
RemoveWebResourceRequestedFilterRemove filter
SetVirtualHostNameToFolderMappingVirtual host mappingSet after Ready, then Navigate
ClearVirtualHostNameToFolderMappingClear mapping
PrintToPdfPrint to PDFRequires page loaded
Suspend / ResumeSuspend/Resume
OpenDevToolsWindowOpen DevTools
CallDevToolsProtocolMethodAsync CDP
CallDevToolsProtocolMethodSyncSync CDP
OpenDefaultDownloadDialogOpen download dialog
CloseDefaultDownloadDialogClose download dialog
OpenTaskManagerWindowTask manager
ResizeResize
SetFocusSet focus
BindUIDOM event bindingRequires page DOM to exist
UnbindUIRemove event binding
BindDataData bindingRequires page DOM to exist
UnbindDataRemove data binding
SetDataPush dataRequires BindData already done
SetDataBatchBatch pushRequires BindData already done
MethodDescription
InitializeInitialize control, the starting point
CleanupClean up resources, can be called anytime

The following methods depend on the page DOM being rendered. It is recommended to call them after the wv_DOMContentLoaded or wv_NavigationComplete event:

MethodDescriptionReason
BindUIDOM event bindingRequires elements already in DOM
BindDataData bindingRequires elements already in DOM
SetData / SetDataBatchPush dataRequires BindData completed
JsRun / JsPropSync JS callsRequires JS environment ready
Script.EvalSync execute JSRequires page JS executable

Best Practice:

vb
Private Sub wv_DOMContentLoaded()
    ' ★ Bind UI and data after DOM is ready
    wv.BindData "name", "#name-input", "value"
    wv.BindData "name", "#name-preview", "textContent"
    wv.BindUI Me, "OnNameInput", "#name-input", EventName:="input"
    wv.SetData "name", "Initial value"
End Sub

⚠️ Common Error Scenarios

Wrong approachProblemCorrect approach
Setting EnvironmentOptions.UserDataFolder in Form_LoadInitialize internally overwrites defaults, but user settings before Create are preservedSet in wv_Create event
Calling Navigate in Create eventCoreWebView not yet created, silently failsNavigate in wv_Ready event
Calling AddObject before ReadyUnderlying CoreWebView is NothingAddObject in wv_Ready event
Calling BindData in NavigationStartingDOM may not yet be loadedBindData in wv_DOMContentLoaded
Setting IsPasswordAutoSaveEnabled in CreateSettings4 object not yet created, may have no effectSet after wv_Ready

🗺️ Quick Decision Flowchart

Need to configure EnvironmentOptions or Security?
  → ★ wv_Create event

Need to set runtime properties (IsPasswordAutoSaveEnabled etc.)?
  → ★ From wv_Ready event onwards

Need to navigate, inject scripts, register filters?
  → ★ From wv_Ready event onwards

Need to bind UI/data, execute JS?
  → ★ From wv_DOMContentLoaded event onwards (ensure DOM is ready)

Need to read state (URL, title, etc.)?
  → ★ Any time (but valid values only after Ready)

Last Updated: 2026-06-26

VB6 and LOGO copyright of Microsoft Corporation