Skip to content

cWebView2Host Methods Reference

📋 Methods Overview

CategoryMethodDescription
LifecycleInitializeInitialize WebView2 control
NavigationNavigateNavigate to specified URL
NavigateCustomCustom request navigation (supports POST/PUT)
NavigateToStringLoad HTML string
GoBackGo backward
GoForwardGo forward
ReloadReload page
ScriptingExecuteScriptExecute JavaScript asynchronously
JsRunCall JS function synchronously
JsRunAsyncCall JS function asynchronously (returns token)
JsPropRead JS property synchronously
MessagingPostWebMessageSend string message to WebView
PostWebMessageJSONSend JSON message to WebView
COM ObjectsAddObjectInject COM host object into JS global
RemoveObjectRemove injected COM host object
Script InjectionAddScriptToExecuteOnDocumentCreatedAuto-execute script on page creation
Resource FilteringAddWebResourceRequestedFilterAdd web resource request filter
RemoveWebResourceRequestedFilterRemove web resource request filter
DevToolsOpenDevToolsWindowOpen DevTools window
CallDevToolsProtocolMethodCall CDP method asynchronously
CallDevToolsProtocolMethodSyncCall CDP method synchronously
Virtual HostSetVirtualHostNameToFolderMappingMap virtual host name to local folder
ClearVirtualHostNameToFolderMappingClear virtual host name mapping
PDFPrintToPdfPrint current page to PDF
Suspend/ResumeSuspendSuspend WebView2 process
ResumeResume suspended WebView2 process
DownloadOpenDefaultDownloadDialogOpen default download dialog
CloseDefaultDownloadDialogClose default download dialog
WindowResizeResize WebView2 control
SetFocusSet focus to WebView2 control
OpenTaskManagerWindowOpen browser task manager
Data BindingBindUIDeclarative DOM event → host method binding
UnbindUIRemove DOM event binding
BindDataDeclarative host data → DOM attribute binding
UnbindDataRemove data binding
SetDataPush single data value to DOM
SetDataBatchBatch push data to DOM

🌐 Lifecycle Methods

Initialize

Initialize the WebView2 control, create environment and controller, and optionally navigate to a specified URL.

vb
Public Function Initialize(HostOrHwnd As Variant, Optional HttpOrDir As String) As cWebView2Host

Parameters:

  • 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 to http://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:

vb
' 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 to the specified URL.

vb
Public Sub Navigate(ByVal Url As String)

Parameters:

  • Url - Target URL address

Example:

vb
wv.Navigate "https://example.com"

Navigate using custom HTTP method and request body.

vb
Public Sub NavigateCustom(ByVal Url As String, ByVal Method As String, ByVal Body As String, Optional ByVal Headers As String)

Parameters:

  • Url - Target URL address
  • Method - HTTP method (e.g., "POST", "PUT", "DELETE")
  • Body - Request body content (UTF-8 encoded)
  • Headers - Optional. Custom request headers in JSON format

Example:

vb
' POST request
wv.NavigateCustom "https://api.example.com/data", "POST", "{""key"":""value""}", "{""Content-Type"":""application/json""}"

Load an HTML string into WebView2 for rendering.

vb
Public Sub NavigateToString(ByVal HtmlContent As String)

Parameters:

  • HtmlContent - Complete HTML string

Example:

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

vb
Public Sub GoBack()
Public Sub GoForward()
Public Sub Reload()

Example:

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

vb
Public Sub ExecuteScript(ByVal JavaScript As String, Optional ByVal Token As Long = 0)

Parameters:

  • JavaScript - JavaScript code to execute
  • Token - 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:

vb
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 Sub

JsRun

Synchronously call a JavaScript function and return the result. Blocks the current thread until JS execution completes.

vb
Public Function JsRun(ByVal Expression As String, Optional ByVal TimeoutMs As Long = 5000) As String

Parameters:

  • Expression - JavaScript expression or function call
  • TimeoutMs - 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:

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

vb
Public Function JsRunAsync(ByVal Expression As String) As Long

Parameters:

  • Expression - JavaScript expression

Returns: Token, used in the JsAsyncResult event to match the corresponding call

Example:

vb
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 Sub

JsProp

Synchronously read a JavaScript property value.

vb
Public Function JsProp(ByVal Expression As String, Optional ByVal TimeoutMs As Long = 5000) As String

Parameters:

  • Expression - JavaScript property expression
  • TimeoutMs - Optional. Timeout in milliseconds, default 5000

Returns: JSON string of the property value

Example:

vb
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', ...).

vb
Public Sub PostWebMessage(ByVal Message As String)

Parameters:

  • Message - Message string to send

Example:

vb
wv.PostWebMessage "Hello from VB6"

PostWebMessageJSON

Send a JSON-formatted message to the WebView2 page.

vb
Public Sub PostWebMessageJSON(ByVal JsonMessage As String)

Parameters:

  • JsonMessage - JSON-formatted message string

Example:

vb
wv.PostWebMessageJSON "{""type"":""update"",""data"":{""name"":""test""}}"

🔗 COM Object Methods

AddObject

Inject a COM object into WebView2's JavaScript global namespace.

vb
Public Sub AddObject(ByVal Name As String, ByVal Object As Object)

Parameters:

  • Name - Global object name in JavaScript
  • Object - 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:

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

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

vb
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:

vb
' 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.

vb
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:

vb
' Intercept all image requests
wv.AddWebResourceRequestedFilter "*", wv2WebResourceContext_Image

' Intercept scripts from specific domain
wv.AddWebResourceRequestedFilter "https://ads.example.com/*", wv2WebResourceContext_Script

RemoveWebResourceRequestedFilter

Remove a previously added resource request filter.

vb
Public Sub RemoveWebResourceRequestedFilter(ByVal Uri As String, ByVal ResourceContext As wv2WebResourceContext)

🔧 DevTools Methods

OpenDevToolsWindow

Open WebView2's developer tools window.

vb
Public Sub OpenDevToolsWindow()

CallDevToolsProtocolMethod

Asynchronously call a Chrome DevTools Protocol method.

vb
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 string
  • CustomEventId - Custom event ID for matching in the DevToolsProtocolResponse event

Note: Results are returned asynchronously via the DevToolsProtocolResponse event.

Example:

vb
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 Sub

CallDevToolsProtocolMethodSync

Synchronously call a Chrome DevTools Protocol method, blocking until the result is returned.

vb
Public Function CallDevToolsProtocolMethodSync(ByVal MethodName As String, ByVal ParametersAsJson As String) As String

Parameters:

  • MethodName - CDP method name
  • ParametersAsJson - 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:

vb
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://.

vb
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 folder
  • AccessKind - Optional. Access permission, default is Allow

Example:

vb
wv.SetVirtualHostNameToFolderMapping "myapp.local", App.Path & "\www"
wv.Navigate "https://myapp.local/index.html"

ClearVirtualHostNameToFolderMapping

Clear a virtual host name mapping.

vb
Public Sub ClearVirtualHostNameToFolderMapping(ByVal HostName As String)

📑 PDF Methods

PrintToPdf

Print the current page to a PDF file.

vb
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 path
  • Orientation - Optional. Print orientation, default is portrait
  • ScaleFactor - 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.

vb
Public Sub Suspend()

Note: Fires SuspendCompleted or SuspendFailed event when complete.


Resume

Resume a suspended WebView2 process.

vb
Public Sub Resume()

📥 Download Methods

OpenDefaultDownloadDialog / CloseDefaultDownloadDialog

Open/close the default download dialog.

vb
Public Sub OpenDefaultDownloadDialog()
Public Sub CloseDefaultDownloadDialog()

🪟 Window Methods

Resize

Resize the WebView2 control to fit the host window.

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

vb
Public Sub SetFocus()

OpenTaskManagerWindow

Open the browser's built-in task manager window.

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

vb
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 String

Parameters:

  • HostInst - Host object instance (typically pass Me, i.e., the Form itself)
  • HostFunction - Public method name on the host object
  • QuerySelector - CSS selector to locate the DOM element
  • IsOverWrite - Optional. Whether to overwrite same-name bindings, default False
  • EventName - 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:

vb
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 Sub

UnbindUI

Remove a DOM event binding.

vb
Public Sub UnbindUI(ByVal QuerySelector As String, Optional ByVal EventName As String = "")

Parameters:

  • QuerySelector - CSS selector used when binding
  • EventName - 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.

vb
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 element
  • Attr - Optional. DOM attribute name, default "textContent". Supports value, textContent, innerHTML, src, class, checked, visible (custom), etc.

Note: The same Key can be bound to multiple elements and different attributes.

Example:

vb
' 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.

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

vb
Public Sub SetData(ByVal Key As String, ByVal Value As Variant)

Parameters:

  • Key - Data key name
  • Value - Data value, supports String, Boolean, Number

Example:

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

vb
Public Sub SetDataBatch(ByVal Json As String)

Parameters:

  • Json - JSON object string where keys are data key names and values are data values

Example:

vb
wv.SetDataBatch "{""name"":""Zhang Wei"",""enabled"":true,""count"":42}"

Last Updated: 2026-06-24

VB6 and LOGO copyright of Microsoft Corporation