cWebView2Host Methods Reference
📋 Methods Overview
| Category | Method | Description |
|---|---|---|
| Lifecycle | Initialize | Initialize WebView2 control |
| Navigation | Navigate | Navigate to specified URL |
| NavigateCustom | Custom request navigation (supports POST/PUT) | |
| NavigateToString | Load HTML string | |
| GoBack | Go backward | |
| GoForward | Go forward | |
| Reload | Reload page | |
| Scripting | ExecuteScript | Execute JavaScript asynchronously |
| JsRun | Call JS function synchronously | |
| JsRunAsync | Call JS function asynchronously (returns token) | |
| JsProp | Read JS property synchronously | |
| Messaging | PostWebMessage | Send string message to WebView |
| PostWebMessageJSON | Send JSON message to WebView | |
| COM Objects | AddObject | Inject COM host object into JS global |
| RemoveObject | Remove injected COM host object | |
| Script Injection | AddScriptToExecuteOnDocumentCreated | Auto-execute script on page creation |
| Resource Filtering | AddWebResourceRequestedFilter | Add web resource request filter |
| RemoveWebResourceRequestedFilter | Remove web resource request filter | |
| DevTools | OpenDevToolsWindow | Open DevTools window |
| CallDevToolsProtocolMethod | Call CDP method asynchronously | |
| CallDevToolsProtocolMethodSync | Call CDP method synchronously | |
| Virtual Host | SetVirtualHostNameToFolderMapping | Map virtual host name to local folder |
| ClearVirtualHostNameToFolderMapping | Clear virtual host name mapping | |
| PrintToPdf | Print current page to PDF | |
| Suspend/Resume | Suspend | Suspend WebView2 process |
| Resume | Resume suspended WebView2 process | |
| Download | OpenDefaultDownloadDialog | Open default download dialog |
| CloseDefaultDownloadDialog | Close default download dialog | |
| Window | Resize | Resize WebView2 control |
| SetFocus | Set focus to WebView2 control | |
| OpenTaskManagerWindow | Open browser task manager | |
| Data Binding | BindUI | Declarative DOM event → host method binding |
| UnbindUI | Remove DOM event binding | |
| BindData | Declarative host data → DOM attribute binding | |
| UnbindData | Remove data binding | |
| SetData | Push single data value to DOM | |
| SetDataBatch | Batch push data to DOM |
🌐 Lifecycle Methods
Initialize
Initialize the WebView2 control, create environment and controller, and optionally navigate to a specified URL.
Public Function Initialize(HostOrHwnd As Variant, Optional HttpOrDir As String) As cWebView2HostParameters:
HostOrHwnd- Host window handle (Long/LongPtr) or VBA object (e.g., Form/Frame). When passing a Form object, hWnd is automatically obtained.HttpOrDir- Optional. URL address (e.g.,"https://vb6.pro") or local folder path (e.g.,App.Path & "\www"). When a folder path is provided, it auto-maps tohttp://vbman2.com/index.html. Omit to skip auto-navigation.
Returns: Returns Me (self), supporting chained calls.
Notes:
- Auto-detects host window class name — OForm uses message window adapter, others use subclassing adapter
- Environment creation has retry logic, up to 10 attempts (auto-incrementing UserDataFolder path)
- Passing a Form object is equivalent to passing
Form.hWnd
Example:
' Minimal two-parameter form: window handle + URL
wv.Initialize Me.hWnd, "https://vb6.pro"
' Pass Form object
wv.Initialize Me, "https://vb6.pro"
' Load local folder
wv.Initialize Me.hWnd, App.Path & "\www"
' Deferred navigation (omit second parameter)
wv.Initialize Me.hWnd
' Manually navigate in wv_Ready event🧭 Navigation Methods
Navigate
Navigate to the specified URL.
Public Sub Navigate(ByVal Url As String)Parameters:
Url- Target URL address
Example:
wv.Navigate "https://example.com"NavigateCustom
Navigate using custom HTTP method and request body.
Public Sub NavigateCustom(ByVal Url As String, ByVal Method As String, ByVal Body As String, Optional ByVal Headers As String)Parameters:
Url- Target URL addressMethod- HTTP method (e.g.,"POST","PUT","DELETE")Body- Request body content (UTF-8 encoded)Headers- Optional. Custom request headers in JSON format
Example:
' POST request
wv.NavigateCustom "https://api.example.com/data", "POST", "{""key"":""value""}", "{""Content-Type"":""application/json""}"NavigateToString
Load an HTML string into WebView2 for rendering.
Public Sub NavigateToString(ByVal HtmlContent As String)Parameters:
HtmlContent- Complete HTML string
Example:
wv.NavigateToString "<html><body><h1>Hello WebView2</h1></body></html>"
' Load from VB6 resource file
wv.NavigateToString VBMAN2.Res(LoadResData("INDEX.HTML", "WWW")).ReturnString()GoBack / GoForward / Reload
Browser navigation controls.
Public Sub GoBack()
Public Sub GoForward()
Public Sub Reload()Example:
If wv.CanGoBack Then wv.GoBack
If wv.CanGoForward Then wv.GoForward
wv.Reload⚡ Script Methods
ExecuteScript
Execute JavaScript code asynchronously — results returned via JsAsyncResult event.
Public Sub ExecuteScript(ByVal JavaScript As String, Optional ByVal Token As Long = 0)Parameters:
JavaScript- JavaScript code to executeToken- Optional. Custom token for identifying the call in the JsAsyncResult event
Note: Executes asynchronously, does not block the VB6 thread. Results are obtained in the JsAsyncResult event.
Example:
wv.ExecuteScript "document.title", 1001
Private Sub wv_JsAsyncResult(ByVal Token As Long, ByVal Result As String, ByVal ErrorCode As Long)
If Token = 1001 Then
Debug.Print "Page title: " & Result
End If
End SubJsRun
Synchronously call a JavaScript function and return the result. Blocks the current thread until JS execution completes.
Public Function JsRun(ByVal Expression As String, Optional ByVal TimeoutMs As Long = 5000) As StringParameters:
Expression- JavaScript expression or function callTimeoutMs- Optional. Timeout in milliseconds, default 5000
Returns: JSON string of JS execution result
Note: Uses Sleep + DoEvents internally for synchronous waiting, does not affect VB6 form message loop.
Example:
Dim title As String
title = wv.JsRun("document.title")
Dim result As String
result = wv.JsRun("JSON.stringify({name:'test', value:42})")JsRunAsync
Asynchronously call a JavaScript function, returning a token for tracking the result in an event.
Public Function JsRunAsync(ByVal Expression As String) As LongParameters:
Expression- JavaScript expression
Returns: Token, used in the JsAsyncResult event to match the corresponding call
Example:
Dim token As Long
token = wv.JsRunAsync("fetch('https://api.example.com/data').then(r=>r.json())")
Private Sub wv_JsAsyncResult(ByVal Token As Long, ByVal Result As String, ByVal ErrorCode As Long)
Debug.Print "Async result token=" & Token & ": " & Result
End SubJsProp
Synchronously read a JavaScript property value.
Public Function JsProp(ByVal Expression As String, Optional ByVal TimeoutMs As Long = 5000) As StringParameters:
Expression- JavaScript property expressionTimeoutMs- Optional. Timeout in milliseconds, default 5000
Returns: JSON string of the property value
Example:
Dim url As String
url = wv.JsProp("location.href")
Dim userAgent As String
userAgent = wv.JsProp("navigator.userAgent")📨 Messaging Methods
PostWebMessage
Send a string message to the WebView2 page. The page receives it via window.chrome.webview.addEventListener('message', ...).
Public Sub PostWebMessage(ByVal Message As String)Parameters:
Message- Message string to send
Example:
wv.PostWebMessage "Hello from VB6"PostWebMessageJSON
Send a JSON-formatted message to the WebView2 page.
Public Sub PostWebMessageJSON(ByVal JsonMessage As String)Parameters:
JsonMessage- JSON-formatted message string
Example:
wv.PostWebMessageJSON "{""type"":""update"",""data"":{""name"":""test""}}"🔗 COM Object Methods
AddObject
Inject a COM object into WebView2's JavaScript global namespace.
Public Sub AddObject(ByVal Name As String, ByVal Object As Object)Parameters:
Name- Global object name in JavaScriptObject- COM object instance
Note: After injection, JS can access the object's methods and properties via window.chrome.webview.hostObjects.<Name>. JS calls to COM methods are asynchronous by default (returning Promises); use hostObjects.sync.<Name> for synchronous calls.
Example:
Dim myObj As New MyComClass
wv.AddObject "myApi", myObj
' In JS:
' const result = await window.chrome.webview.hostObjects.myApi.DoSomething("param");
' const result = window.chrome.webview.hostObjects.sync.myApi.DoSomething("param");RemoveObject
Remove an injected COM host object.
Public Sub RemoveObject(ByVal Name As String)Parameters:
Name- Previously injected object name
💉 Script Injection Methods
AddScriptToExecuteOnDocumentCreated
Script that auto-executes when a page document is created, applies to all subsequent navigated pages.
Public Sub AddScriptToExecuteOnDocumentCreated(ByVal JavaScript As String)Parameters:
JavaScript- JavaScript code to inject
Note: Script executes before DOM has finished loading — suitable for injecting global variables, overriding native methods, etc. Must be called after WebView2 is created.
Example:
' Inject global debug flag
wv.AddScriptToExecuteOnDocumentCreated "window.__vb6Debug = true;"
' Intercept console.log
wv.AddScriptToExecuteOnDocumentCreated _
"window.console.log = function(msg) { window.chrome.webview.postMessage('[LOG] ' + msg); };"🔍 Resource Filtering Methods
AddWebResourceRequestedFilter
Add a web resource request filter. Matching requests trigger the WebResourceRequested event.
Public Sub AddWebResourceRequestedFilter(ByVal Uri As String, ByVal ResourceContext As wv2WebResourceContext)Parameters:
Uri- URI match pattern (supports wildcards)ResourceContext- Resource context type (e.g.,wv2WebResourceContext_Document)
Example:
' Intercept all image requests
wv.AddWebResourceRequestedFilter "*", wv2WebResourceContext_Image
' Intercept scripts from specific domain
wv.AddWebResourceRequestedFilter "https://ads.example.com/*", wv2WebResourceContext_ScriptRemoveWebResourceRequestedFilter
Remove a previously added resource request filter.
Public Sub RemoveWebResourceRequestedFilter(ByVal Uri As String, ByVal ResourceContext As wv2WebResourceContext)🔧 DevTools Methods
OpenDevToolsWindow
Open WebView2's developer tools window.
Public Sub OpenDevToolsWindow()CallDevToolsProtocolMethod
Asynchronously call a Chrome DevTools Protocol method.
Public Sub CallDevToolsProtocolMethod(ByVal MethodName As String, ByVal ParametersAsJson As String, ByVal CustomEventId As String)Parameters:
MethodName- CDP method name (e.g.,"Runtime.evaluate","Network.getCookies")ParametersAsJson- Method parameters as JSON stringCustomEventId- Custom event ID for matching in theDevToolsProtocolResponseevent
Note: Results are returned asynchronously via the DevToolsProtocolResponse event.
Example:
wv.CallDevToolsProtocolMethod "Runtime.evaluate", _
"{""expression"":""document.title""}", "getTitle"
Private Sub wv_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String)
If CustomEventId = "getTitle" Then
Debug.Print "CDP Title: " & JsonResponse
End If
End SubCallDevToolsProtocolMethodSync
Synchronously call a Chrome DevTools Protocol method, blocking until the result is returned.
Public Function CallDevToolsProtocolMethodSync(ByVal MethodName As String, ByVal ParametersAsJson As String) As StringParameters:
MethodName- CDP method nameParametersAsJson- Method parameters as JSON string
Returns: JSON string of CDP response
Note: Uses Sleep + DoEvents for synchronous waiting, does not affect VB6 form message loop.
Example:
Dim cookies As String
cookies = wv.CallDevToolsProtocolMethodSync("Network.getCookies", "{}")
Dim version As String
version = wv.CallDevToolsProtocolMethodSync("Browser.getVersion", "{}")🗂️ Virtual Host Methods
SetVirtualHostNameToFolderMapping
Map a virtual host name to a local folder, allowing WebView2 to access local files via https://.
Public Sub SetVirtualHostNameToFolderMapping(ByVal HostName As String, ByVal FolderPath As String, Optional ByVal AccessKind As wv2HostResourceAccessKind = wv2HostResourceAccessKind_Allow)Parameters:
HostName- Virtual host name (e.g.,"myapp.local")FolderPath- Absolute path to the local folderAccessKind- Optional. Access permission, default is Allow
Example:
wv.SetVirtualHostNameToFolderMapping "myapp.local", App.Path & "\www"
wv.Navigate "https://myapp.local/index.html"ClearVirtualHostNameToFolderMapping
Clear a virtual host name mapping.
Public Sub ClearVirtualHostNameToFolderMapping(ByVal HostName As String)📑 PDF Methods
PrintToPdf
Print the current page to a PDF file.
Public Sub PrintToPdf(ByVal ResultFilePath As String, _
Optional ByVal Orientation As wv2PrintOrientation = wv2PrintOrientation_Portrait, _
Optional ByVal ScaleFactor As Single = 1.0, _
Optional ByVal PageWidth As Single = 0, _
Optional ByVal PageHeight As Single = 0, _
Optional ByVal MarginTop As Single = 0, _
Optional ByVal MarginBottom As Single = 0, _
Optional ByVal MarginLeft As Single = 0, _
Optional ByVal MarginRight As Single = 0, _
Optional ByVal ShouldPrintHeader As Boolean = False, _
Optional ByVal ShouldPrintFooter As Boolean = False)Parameters:
ResultFilePath- PDF output file pathOrientation- Optional. Print orientation, default is portraitScaleFactor- Optional. Scale factor, default 1.0- Remaining parameters are page size and margin settings
Note: Fires PrintToPdfCompleted event on success, PrintToPdfFailed event on failure.
🔌 Suspend/Resume Methods
Suspend
Suspend the WebView2 rendering process to save resources.
Public Sub Suspend()Note: Fires SuspendCompleted or SuspendFailed event when complete.
Resume
Resume a suspended WebView2 process.
Public Sub Resume()📥 Download Methods
OpenDefaultDownloadDialog / CloseDefaultDownloadDialog
Open/close the default download dialog.
Public Sub OpenDefaultDownloadDialog()
Public Sub CloseDefaultDownloadDialog()🪟 Window Methods
Resize
Resize the WebView2 control to fit the host window.
Public Sub Resize()Note: Call when the host window size changes — internally reads the host window client area dimensions.
SetFocus
Set focus to the WebView2 control.
Public Sub SetFocus()OpenTaskManagerWindow
Open the browser's built-in task manager window.
Public Sub OpenTaskManagerWindow()🔗 Data Binding Methods
BindUI
Declaratively bind a DOM event to a host VB method. When the specified element triggers the event, the specified method on the host object is automatically called.
Public Function BindUI(ByVal HostInst As Object, ByVal HostFunction As String, ByVal QuerySelector As String, Optional ByVal IsOverWrite As Boolean = False, Optional ByVal EventName As String = "click") As StringParameters:
HostInst- Host object instance (typically passMe, i.e., the Form itself)HostFunction- Public method name on the host objectQuerySelector- CSS selector to locate the DOM elementIsOverWrite- Optional. Whether to overwrite same-name bindings, default FalseEventName- Optional. DOM event name, default"click"
Returns: BindId, for identifying this binding
Note: Host method signature must be Public Sub MethodName(ByVal EventName As String, ByVal Detail As String), where Detail is a JSON-formatted event detail.
Example:
Dim bindId As String
bindId = wv.BindUI(Me, "OnButtonClick", "#submit-btn")
' With custom event name
wv.BindUI Me, "OnNameInput", "#name-input", EventName:="input"
' Callback method
Public Sub OnButtonClick(ByVal EventName As String, ByVal Detail As String)
Debug.Print "Button clicked! Detail: " & Detail
End SubUnbindUI
Remove a DOM event binding.
Public Sub UnbindUI(ByVal QuerySelector As String, Optional ByVal EventName As String = "")Parameters:
QuerySelector- CSS selector used when bindingEventName- Optional. Specify a particular event to remove; empty removes all bindings for that element
BindData
Declaratively bind a data key to a DOM attribute. When SetData updates the key, all bound DOM attributes are automatically updated.
Public Sub BindData(ByVal Key As String, ByVal QuerySelector As String, Optional ByVal Attr As String = "textContent")Parameters:
Key- Data key name (custom identifier)QuerySelector- CSS selector to locate the DOM elementAttr- Optional. DOM attribute name, default"textContent". Supportsvalue,textContent,innerHTML,src,class,checked,visible(custom), etc.
Note: The same Key can be bound to multiple elements and different attributes.
Example:
' Same data bound to input value and preview text
wv.BindData "name", "#name-input", "value"
wv.BindData "name", "#name-preview", "textContent"
' Bind to checkbox checked attribute
wv.BindData "enabled", "#toggle-enabled", "checked"
' Bind to custom visible attribute (control show/hide)
wv.BindData "enabled", "#settings-panel", "visible"
' Bind to image src
wv.BindData "avatar", "#avatar-img", "src"
' Bind to CSS class
wv.BindData "statusOnline", "#status-dot", "class"UnbindData
Remove a data binding.
Public Sub UnbindData(ByVal Key As String)Parameters:
Key- Data key name to remove
SetData
Push a single data value to all bound DOM elements.
Public Sub SetData(ByVal Key As String, ByVal Value As Variant)Parameters:
Key- Data key nameValue- Data value, supports String, Boolean, Number
Example:
wv.SetData "name", "Zhang Wei"
wv.SetData "enabled", True
wv.SetData "count", 42
wv.SetData "avatar", "https://example.com/img.png"SetDataBatch
Batch push data to DOM; parameter is a JSON object string.
Public Sub SetDataBatch(ByVal Json As String)Parameters:
Json- JSON object string where keys are data key names and values are data values
Example:
wv.SetDataBatch "{""name"":""Zhang Wei"",""enabled"":true,""count"":42}"Last Updated: 2026-06-24