Skip to content

cWebView2Host Class Developer Documentation

🚀 cWebView2Host - A VB6/twinBASIC embedded browser control wrapper based on Microsoft Edge WebView2, developed by woeoio@qq.com using the WebView2 Win32 C API

📖 Table of Contents


Overview

cWebView2Host is a COM-creatable class that provides Microsoft Edge WebView2 embedded browser capabilities for VB6/VBA/twinBASIC applications. It encapsulates the full complexity of the WebView2 Win32 C API, providing a clean VB-style API, a complete event model, and a declarative data binding system.

✨ Key Features

  • 🌐 Zero-Configuration Embedding - Embed a full Chromium browser in a form with just two lines of code
  • 📡 40+ Events - Covering navigation, scripting, mouse, keyboard, downloads, PDF printing, and more
  • 🔗 Declarative Data Binding - BindUI/BindData two-way binding, zero glue code between VB6 and DOM
  • Synchronous JS Calls - JsRun/JsProp execute JavaScript synchronously, no more async callback hell
  • 🔧 Full CDP Support - Synchronous/asynchronous Chrome DevTools Protocol calls for deep browser control
  • 🛡️ Security Controls - Certificate error bypass, HTTPS filtering, script toggle in one-stop configuration
  • 🍪 Cookie Management - Simple/full dual-mode Cookie retrieval, including HttpOnly support
  • 📦 Local Resource Mapping - Three local page loading methods: folder, resource file, and virtual host
  • 🖥️ Multi-Host Adaptation - VB6/Excel subclassing + Access message window dual-strategy auto-detection
  • 📑 Session Isolation - Multi-instance independent UserDataFolder, supporting multi-account parallelism

Core Highlights

1️⃣ Two Lines to Embed a Browser 🌐

No configuration files or initialization steps needed — minimal usage requires just two calls:

vb
Dim wv As New cWebView2Host

Private Sub Form_Load()
    wv.Initialize Me.hWnd, "https://vb6.pro"
End Sub

One line of declaration, one line of initialization — a full Edge browser engine in your form instantly.


2️⃣ Declarative Two-Way Data Binding 🔗

Zero glue code two-way binding between VB6 and Web UI — declare instead of command:

vb
' Host -> UI: Bind key to DOM attribute
wv.BindData "name", "#name-input", "value"
wv.BindData "name", "#name-preview", "textContent"

' UI -> Host: Bind DOM event to VB6 method
wv.BindUI Me, "OnNameInput", "#name-input", EventName:="input"

' Push data to UI
wv.SetData "name", "Zhang Wei"

3️⃣ Synchronous JavaScript Execution ⚡

No callbacks needed — get JS return values synchronously in VB6:

vb
' Synchronously call JS function and get return value
Dim title As String
title = wv.JsRun("document.title")

' Synchronously read JS property
Dim url As String
url = wv.JsProp("location.href")

' Synchronously execute CDP command
Dim cookies As String
cookies = wv.CallDevToolsProtocolMethodSync("Network.getCookies", "{}")

4️⃣ Complete Event-Driven Model 📡

Covering all WebView2 lifecycle events — from creation to destruction, from navigation to interaction:

vb
Dim WithEvents wv As cWebView2Host

' Lifecycle
Private Sub wv_Create(): ...
Private Sub wv_Ready(): ...

' Navigation control
Private Sub wv_NavigationStarting(ByVal Uri As String, ByRef Cancel As Boolean): ...
Private Sub wv_NavigationComplete(ByVal IsSuccess As Boolean): ...

' Host mouse/keyboard
Private Sub wv_HostMouseDown(ByVal Button As Long, ByVal Shift As Long, ByVal X As Long, ByVal Y As Long): ...

' JS messages
Private Sub wv_JsMessage(ByVal Message As String): ...

5️⃣ Multi-Host Auto-Adaptation 🖥️

The same API automatically adapts to three host environments: VB6, Excel UserForm, and Access OForm:

vb
' All three hosts use exactly the same API
wv.Initialize Me.hWnd, "https://vb6.pro"        ' VB6 / Excel UserForm
wv.Initialize Me, "https://vb6.pro"              ' Pass Form object (auto-detected)
' Access forms auto-detect OForm class name, switching to MessageWindowAdapter

Internally detects the host window class name — VB6/Excel uses the subclassing adapter, Access uses the message window adapter.


Quick Start

Minimal Example

vb
Dim wv As New cWebView2Host

Private Sub Form_Load()
    wv.Initialize Me.hWnd, "https://vb6.pro"
End Sub

Example with Event Handling

vb
Dim WithEvents wv As cWebView2Host

Private Sub Form_Load()
    Set wv = New cWebView2Host
    wv.Initialize Me.hWnd, "https://vb6.pro"
End Sub

Private Sub wv_Ready()
    Me.Caption = wv.DocumentTitle
    Debug.Print "Browser is ready"
End Sub

Private Sub wv_DocumentTitleChanged()
    Me.Caption = wv.DocumentTitle
End Sub

Loading Local HTML Files

vb
' Method 1: Folder path auto-mapping
wv.Initialize Me.hWnd, App.Path & "\www"

' Method 2: Virtual host name mapping
wv.Initialize Me.hWnd
wv.SetVirtualHostNameToFolderMapping "myapp.local", App.Path & "\www"
wv.Navigate "https://myapp.local/index.html"

' Method 3: Load from VB6 resource file
wv.Initialize Me.hWnd
' In the wv_Ready event:
wv.NavigateToString VBMAN2.Res(LoadResData("INDEX.HTML", "WWW")).ReturnString()

Architecture Design

Class Hierarchy

cWebView2Host (Public COM class, direct user interaction)
├── m_Core: WebView2Core (Core engine, implements 21 COM callback interfaces)
│   ├── ICoreWebView2 ~ ICoreWebView2_9 (Versioned interface cache)
│   ├── ICoreWebView2Settings ~ Settings6
│   ├── ICoreWebView2Environment ~ _8
│   └── All event delegate Token management

├── m_Cookies: cWebView2Cookies (Cookie management business object)
│   └── GetCookies / GetCookiesFull / GetCookiesFullAsync

├── m_Script: cWebView2Script (Script execution business object)
│   └── Eval (Synchronous JS expression evaluation)

├── m_Security: cWebView2Security (Security/certificate management business object)
│   └── CertificateErrorAction / AdditionalBrowserArguments

├── m_MouseProxy: WebView2MouseProxy (JS->Host mouse event COM proxy)
│   └── Exposed as JS global object mouseProxy

├── m_BindUIProxy: WebView2BindUIProxy (Declarative binding COM proxy)
│   ├── Exposed as JS global object bindUIProxy
│   ├── BindUI event binding management
│   ├── BindData data binding management
│   └── Auto-rebuild bindings after navigation

└── Adapter: IHostAdapter (Host adaptation abstraction layer)
    ├── HostSubclassAdapter (VB6/Excel, subclassing host window)
    └── MessageWindowAdapter (Access, message window + polling)

Object Relationship Diagram

User Code


cWebView2Host ──────── Event Forwarding ──────── WebView2Core (WithEvents)
  │                                         │
  ├── Cookies ──────────────────────────────┤ CDP / document.cookie
  ├── Script ───────────────────────────────┤ ExecuteScript / JsRun
  ├── Security ─────────────────────────────┤ AdditionalBrowserArguments
  │                                         │
  ├── BindUIProxy ◄── AddObject ────────────┤ JS global object bindUIProxy
  └── MouseProxy  ◄── AddObject ────────────┤ JS global object mouseProxy
                    ──────────────────────────┘

                    IHostAdapter (Adapter Layer)
                    ┌─────────┴─────────┐
              HostSubclassAdapter  MessageWindowAdapter
              (VB6/Excel subclassing)   (Access message window)

Initialization Flow

1. cWebView2Host.Initialize(HostOrHwnd, HttpOrDir)
2. Auto-detect host window class name
   ├── "OForm" → Create MessageWindowAdapter
   └── Other   → Create HostSubclassAdapter
3. Adapter.Attach() → Subclass host window / Create message window
4. Create WebView2 Environment (with retry logic, up to 10 attempts)
5. Create WebView2 Controller
6. CacheWebViewObjects() → QI cache ICoreWebView2_1~9
7. CacheSettingsObjects() → QI cache Settings_1~6
8. Inject MouseProxy / BindUIProxy COM objects
9. Fire Create event
10. If URL specified → Auto-navigate
11. Navigation complete → Fire Ready event

Three-Phase Initialization Pattern

For scenarios requiring environment configuration before navigation, use the three-phase pattern:

Phase 1: Initialize (no URL)       → Create WebView2 control
Phase 2: wv_Create event           → Configure EnvironmentOptions / Security
Phase 3: wv_Ready event            → Execute Navigate / NavigateToString
vb
Private Sub Form_Load()
    Set wv = New cWebView2Host
    wv.Initialize Me.hWnd              ' Phase 1: No URL
End Sub

Private Sub wv_Create()
    wv.EnvironmentOptions.UserDataFolder = App.Path & "\UserDir\account-001"
    wv.Security.CertificateErrorAction = CEA_AlwaysAllow   ' Phase 2: Configure
End Sub

Private Sub wv_Ready()
    wv.Navigate "https://example.com"  ' Phase 3: Navigate
End Sub

Documentation Index

DocumentDescription
Methods ReferenceComplete public methods API reference for cWebView2Host
Properties ReferenceComplete public properties API reference for cWebView2Host
Events ReferenceDetailed description of all cWebView2Host events
Data Binding GuideBindUI/BindData/SetData two-way binding system
CDP GuideChrome DevTools Protocol calling guide
Host Adaptation GuideVB6/Excel/Access multi-host integration guide
FAQCommon questions and solutions during development

Dependencies

ComponentDescription
Microsoft Edge WebView2 RuntimeRuntime dependency, must be installed on target machine
vbman2_win32.dllVBMAN2 type library, provides COM registration
WebView2 Win32 C APIUnderlying COM interfaces, encapsulated by interface definitions in Abstract/ directory

Compatibility

  • VB6 - Fully compatible, supports subclassing adapter
  • VBA (Excel) - Fully compatible, uses subclassing adapter in UserForms
  • VBA (Access) - Fully compatible, automatically uses message window adapter
  • twinBASIC - Fully compatible, native development language
  • Windows - Windows 10 and above (WebView2 Runtime requirement)
  • WebView2 Runtime - Version 86.0.616.0 and above

License

Based on the Microsoft WebView2 SDK


Author

cWebView2Host: woeoio@qq.com


Last Updated: 2026-06-24

VB6 and LOGO copyright of Microsoft Corporation