ILiteView2Ctrl Interface coclass LiteView2Ctrl | Design-time OCX pattern | No browserIndex parameter

Note

Default dispinterface: _LiteView2Ctrl | Event source: _DLiteView2CtrlEvents

Local Content Mapping 4 methods

Map local folders and custom URI schemes to virtual hostnames for secure local content serving.

MemberParametersReturnsDescription
SetLocalContentRootfolderPath As StringMap local folder to https://lv2.local/ virtual hostname
SetVirtualHostNameToFolderMappinghostName, folderPath As String, accessKind As LongMap any hostname to local folder
ClearVirtualHostNameToFolderMappinghostName As StringRemove virtual hostname mapping
AddCustomSchemeRegistrationschemeName As String, treatAsSecure As BooleanRegister custom URI scheme (e.g., myapp://)

Per-Member Usage

' SetLocalContentRoot — map folder to https://lv2.local/
m_lv.SetLocalContentRoot CurrentProject.Path & "\demos"
m_lv.Navigate "https://lv2.local/index.html"

' SetVirtualHostNameToFolderMapping — map any hostname
m_lv.SetVirtualHostNameToFolderMapping "assets.local", "C:\MyApp\Assets", 0
' accessKind: 0=Deny, 1=Allow, 2=DenyCors
' Now use: https://assets.local/images/logo.png

' ClearVirtualHostNameToFolderMapping — remove mapping
m_lv.ClearVirtualHostNameToFolderMapping "assets.local"

' AddCustomSchemeRegistration — register custom URI scheme
m_lv.AddCustomSchemeRegistration "myapp", True
' Now myapp://resource/path will be handled by WebResourceRequested event
State Properties 14 properties

Read-only and read/write properties reflecting the current state of the WebView2 browser instance.

PropertyTypeR/WDescription
UrlStringR/WCurrent URL (default property)
DocumentTitleStringRCurrent page title
IsLoadingBooleanRWhether page is currently loading
CanGoBackBooleanRWhether back navigation is available
CanGoForwardBooleanRWhether forward navigation is available
LastErrorStringRLast error message
LastErrorCodeLongRLast error code (numeric)
ContainsFullScreenElementBooleanRWhether page has fullscreen element
StatusBarTextStringRCurrent status bar text
WebViewCreatedBooleanRWhether WebView has been created and is ready
InPrivateModeBooleanRWhether browser is in InPrivate mode
FaviconUriStringRFavicon URI of current page
BrowserProcessIdLongRBrowser subprocess PID
BrowserProcessIDLongLongRVB6-friendly alias for BrowserProcessId

Per-Member Usage

' Url (R/W) — current URL; also the default property
Debug.Print m_lv.Url                        ' "https://lv2.local/page.html"
m_lv.Url = "https://www.example.com"       ' same as Navigate

' DocumentTitle (R) — page <title>
Debug.Print "Title: " & m_lv.DocumentTitle

' IsLoading (R) — True while page is loading
If m_lv.IsLoading Then m_lv.Stop

' CanGoBack / CanGoForward (R) — history state
btnBack.Enabled = m_lv.CanGoBack
btnFwd.Enabled = m_lv.CanGoForward

' LastError / LastErrorCode (R) — last error info
If m_lv.LastErrorCode <> 0 Then
    MsgBox "Error " & m_lv.LastErrorCode & ": " & m_lv.LastError
End If

' ContainsFullScreenElement (R) — fullscreen video etc.
Debug.Print "Fullscreen: " & m_lv.ContainsFullScreenElement

' StatusBarText (R) — hover-link text
lblStatus.Caption = m_lv.StatusBarText

' WebViewCreated (R) — True after WebView2 is ready
If m_lv.WebViewCreated Then m_lv.Navigate "https://example.com"

' InPrivateMode (R) — InPrivate browsing
Debug.Print "InPrivate: " & m_lv.InPrivateMode

' FaviconUri (R) — page favicon URL
Debug.Print "Favicon: " & m_lv.FaviconUri

' BrowserProcessId / BrowserProcessIDLong (R) — PID
Debug.Print "PID: " & m_lv.BrowserProcessId
Debug.Print "PID (VB6): " & m_lv.BrowserProcessIDLong  ' same value, VB6-friendly
Readiness Check 1 method

Check whether the WebView2 engine has been fully initialized.

MemberParametersReturnsDescription
IsReadyBooleanCheck if WebView2 is ready
Tip

Primary readiness signal is the WebViewReady event. Use IsReady only as a guard clause or polling fallback.

Timer Fallback Pattern

Source: frmCustomerDetail_Code.txt

' Timer fallback pattern (optional — not needed on correctly registered OCX)
Private Sub tmrReady_Timer()
    If m_lv.IsReady Then
        tmrReady.Enabled = False
        LoadCustomerData
    End If
End Sub
Script Execution 6 methods

Execute JavaScript in the WebView2 browser and retrieve results.

MemberParametersReturnsDescription
ExecuteScriptscript As StringStringExecute JS synchronously, return result
ExecuteScriptAsyncscript As StringExecute JS asynchronously (fire and forget)
ExecuteScriptWithArgsfunctionName As String, arguments As VariantStringCall JS function with VBA arguments (Array, Recordset, or scalar). Auto-serializes to JSON.
ExecuteScriptWithResultscript As StringresultAsJson As String, succeeded As Boolean, exceptionMessage As StringExecute script with detailed result + exception info
AddScriptToExecuteOnDocumentCreatedscript As StringString (scriptId)Inject JS that runs on every page load
RemoveScriptToExecuteOnDocumentCreatedid As StringRemove injected script

Per-Member Usage

' ExecuteScript — run JS synchronously, get return value
Dim title As String
title = m_lv.ExecuteScript("document.title")

' ExecuteScriptAsync — fire-and-forget (no return value)
m_lv.ExecuteScriptAsync "console.log('Hello from VBA')"

' ExecuteScriptWithArgs — call JS function with auto-serialized VBA args
Dim result As String
result = m_lv.ExecuteScriptWithArgs("testFunction", Array("Hello", 42, True))

' ExecuteScriptWithResult — detailed result + exception info (ByRef params)
Dim resultJson As String, succeeded As Boolean, exMsg As String
m_lv.ExecuteScriptWithResult "1 + 2", resultJson, succeeded, exMsg
If succeeded Then Debug.Print resultJson  ' "3"

' AddScriptToExecuteOnDocumentCreated — inject JS on every page load
Dim scriptId As String
scriptId = m_lv.AddScriptToExecuteOnDocumentCreated("document.title += ' [LV2]';")

' RemoveScriptToExecuteOnDocumentCreated — remove injected script by ID
m_lv.RemoveScriptToExecuteOnDocumentCreated scriptId
Data Bridge — VBA to JS 7 methods

Send data from VBA to JavaScript. Includes native recordset serialization and JSON messaging.

MemberParametersReturnsDescription
PostWebMessageAsJsonwebMessageAsJson As StringPost JSON message to JS. JS receives via window.chrome.webview.addEventListener('message', ...)
PostWebMessageAsStringwebMessageAsString As StringPost string message to JS
PushRecordsetrecordset As Object, jsCallback As StringPush DAO/ADO Recordset as JSON array. Calls window[jsCallback](jsonArray) in JS.
BuildJsoninputData As VariantStringConvert VBA data to JSON string. See JSON Helpers.
FireJsEventeventName As String, jsonData As StringFire a CustomEvent in the page. JS listens with addEventListener or window.lv.on()
CallJsFunctionfuncPath As String, jsonArgs As StringCall JS function by dot-path with JSON args
SetJsVariablepath As String, jsonValue As StringSet a JS variable

Per-Member Usage

' PostWebMessageAsJson — send JSON to JS (received via chrome.webview message event)
m_lv.PostWebMessageAsJson "{""type"":""update"",""id"":42}"

' PostWebMessageAsString — send plain string to JS
m_lv.PostWebMessageAsString "Hello from VBA"

' PushRecordset — push DAO/ADO Recordset as JSON array to a JS callback
Dim rs As DAO.Recordset
Set rs = db.OpenRecordset("SELECT * FROM tblSales", dbOpenSnapshot)
m_lv.PushRecordset rs, "onSalesData"    ' JS: window.onSalesData(jsonArray)
rs.Close

' BuildJson — convert VBA value/array to JSON string (no WebView2 needed)
Dim json As String
json = m_lv.BuildJson(Array("apple", "banana"))  ' '["apple","banana"]'

' FireJsEvent — dispatch a CustomEvent in the page
m_lv.FireJsEvent "vbaDataReady", "{""source"":""VBA""}"
' JS: document.addEventListener("vbaDataReady", e => console.log(e.detail))

' CallJsFunction — call JS function by dot-path with JSON args
m_lv.CallJsFunction "app.handlers.onData", "{""action"":""refresh""}"

' SetJsVariable — set a JS variable from VBA
m_lv.SetJsVariable "window.vbaConfig", "{""theme"":""dark""}"
window.lv Facade 2 members

Enable or check the window.lv global JavaScript facade for simplified messaging.

MemberParametersReturnsDescription
EnableLvFacadeenabled As BooleanInject window.lv global JS facade. Call BEFORE first Navigate.
IsLvFacadeEnabledBooleanWhether window.lv facade is active

Facade Example

Source: frmScriptBridge_Code.txt

' Enable the window.lv facade BEFORE first Navigate
m_lv.EnableLvFacade True
m_lv.Navigate "https://lv2.local/my_page.html"

' Check if facade is active
If m_lv.IsLvFacadeEnabled Then Debug.Print "window.lv is available in JS"
JSON Helpers 7 methods
Note

These methods work without WebView2 — pure VBA JSON utilities.

MemberParametersReturnsDescription
BuildJsoninputData As VariantStringConvert VBA value/array to JSON
JsonGetValuejsonString As String, path As StringVariantExtract value by JSONPath
JsonGetArrayLengthjsonString As String, path As StringLongGet array length at path
JsonGetArrayItemjsonString As String, path As String, index As LongStringGet array item as JSON string
JsonGetKeysjsonString As String, path As StringStringGet all keys from object at path
JsonIsValidjsonString As StringBooleanValidate JSON syntax
JsonToArrayjsonArrayString As StringVariant (String)Validate and return JSON string. For 2D array output, use JsonToRowArray instead. Respects JsonToArrayMaxSize (default 50 MB).
Tip

All JSON helper methods work without WebView2 — safe to call from any context, including inside event handlers such as WebMessageReceived.

JsonGetValue — Return Type Mapping

JsonGetValue returns a typed Variant whose VBA type depends on the JSON value:

JSON ValueVBA TypeExample
StringString"Jane""Jane"
IntegerLong4242
DecimalDouble3.143.14
BooleanBooleantrueTrue
NullNullnullNull (use IsNull() to check)
Object / ArrayString{"a":1} → raw JSON string
Key not foundNull(path absent) → Null
IBrowserPool Difference

JsonGetValue behaves differently on each interface:

  • ILiteView2Ctrl (design-time OCX) → returns typed Variant (Long, Double, Boolean, Null, String)
  • IBrowserPool (reg-free) → always returns String

This affects type checking, Null handling, and numeric comparisons. When using IBrowserPool, use CLng() or CDbl() to convert numeric results.

Per-Member Usage

' BuildJson — convert VBA value/array to JSON string
Dim j As String
j = m_lv.BuildJson(Array(1, 2, 3))        ' "[1,2,3]"
j = m_lv.BuildJson("hello")               ' "\"hello\""

' JsonGetValue — extract value by JSONPath
Dim v As Variant
v = m_lv.JsonGetValue("{""name"":""Jane"",""age"":30}", "name")  ' "Jane"
v = m_lv.JsonGetValue("{""a"":{""b"":5}}", "a.b")              ' 5

' JsonGetArrayLength — count elements at path
Dim count As Long
count = m_lv.JsonGetArrayLength("[10,20,30]", "")  ' 3

' JsonGetArrayItem — get array element as JSON string
Dim item As String
item = m_lv.JsonGetArrayItem("[{""id"":1},{""id"":2}]", "", 0)  ' '{"id":1}'

' JsonGetKeys — list all keys from a JSON object
Dim keys As String
keys = m_lv.JsonGetKeys("{""name"":""Jane"",""age"":30}", "")  ' '["name","age"]'

' JsonIsValid — check if string is valid JSON
If m_lv.JsonIsValid(myJson) Then Debug.Print "Valid!"

' JsonToArray — validate JSON and return as String
Dim validated As Variant
validated = m_lv.JsonToArray("[{""name"":""Alice""},{""name"":""Bob""}]")
' Returns the validated JSON string (not a 2D array)
' For 2D array output, use JsonToRowArray instead
JSON Mutation 16 methods
Fail-Safe Contract

All JSON mutation functions follow a fail-safe contract:

  • Never throw COM errors to the caller
  • Return the original JSON string unchanged on any failure
  • Error details are available via the LastError property
  • All work without WebView2 — they can be called even before the browser is created
IBrowserPool Naming

On IBrowserPool, three methods have historical 2-suffix aliases: JsonSetValue2, JsonRemoveKey2, JsonToRowArray2. Both names work — the non-suffix versions (JsonSetValue, JsonRemoveKey, JsonToRowArray) are preferred and match the names shown here.

MemberParametersReturnsDescription
JsonCreateObjectStringReturns "{}"
JsonCreateArrayStringReturns "[]"
JsonSetValuejsonString As String, path As String, value As VariantStringSet or create a value at path. Auto-creates intermediate objects/arrays.
JsonRemoveKeyjsonString As String, path As StringStringRemove a key or array element by path
JsonExistsjsonString As String, path As StringBooleanCheck if a path exists in JSON
JsonAppendjsonString As String, path As String, value As VariantStringAppend value to array at path. Auto-creates array if missing.
JsonInsertjsonString As String, path As String, index As Long, value As VariantStringInsert value at specific array position
JsonMergejson1 As String, json2 As String, deepMerge As BooleanStringMerge two JSON objects. deepMerge=True for recursive merge.
JsonCountjsonString As String, path As StringLongCount keys (object) or elements (array) at path
JsonClearjsonString As String, path As StringStringEmpty a container at path ({} or [])
JsonPrettyPrintjsonString As StringStringFormat JSON with 2-space indentation (max 5 MB input)
JsonFlattenjsonString As StringStringFlatten nested JSON to dot-notation keys
JsonUnflattenjsonString As StringStringUnflatten dot-notation keys back to nested JSON
JsonToRowArrayjsonString As StringVariant (2D array)Convert JSON array of objects to 2D VBA array (row 1 = headers, typed values). Respects JsonToArrayMaxSize.
JsonUnwrapStringjsonValue As StringStringIf jsonValue is a JSON string literal (double-encoded by ExecuteScriptWithResult), unwrap one layer and unescape all sequences. Otherwise return unchanged.
JsonCompactjsonString As String, path As StringStringRemove null entries from a JSON array at path. Pass empty string for root array.
When to Use What

Reading: JsonGetValue, JsonGetArrayLength, JsonGetArrayItem, JsonGetKeys, JsonExists, JsonCount

Building: JsonCreateObject / JsonCreateArrayJsonSetValue, JsonAppend, JsonInsert

Modifying: JsonRemoveKey, JsonClear, JsonMerge

Converting: BuildJson (VBA→JSON), JsonToRowArray (JSON→2D array), JsonFlatten / JsonUnflatten, JsonUnwrapString (unwrap double-encoded strings)

Cleaning: JsonCompact (remove nulls from arrays)

Debugging: JsonPrettyPrint, JsonIsValid

Per-Member Usage

' ── Create ──
' JsonCreateObject / JsonCreateArray — starting points
Dim json As String
json = m_lv.JsonCreateObject()                     ' "{}"

' ── Set Values ──
' JsonSetValue — set or create value at any path
json = m_lv.JsonSetValue(json, "name", "Imran")
json = m_lv.JsonSetValue(json, "address.city", "London")
' {"name":"Imran","address":{"city":"London"}}

' Overwrite existing value
json = m_lv.JsonSetValue(json, "name", "Ali")

' Auto-create array with null padding
json = m_lv.JsonSetValue(json, "scores[2]", 95)
' scores = [null, null, 95]

' ── Remove ──
' JsonRemoveKey — remove key or array element
json = "{""name"":""Imran"",""age"":30,""temp"":true}"
json = m_lv.JsonRemoveKey(json, "temp")
' {"name":"Imran","age":30}

' Remove array element (remaining elements shift)
json = "{""items"":[10,20,30]}"
json = m_lv.JsonRemoveKey(json, "items[1]")
' {"items":[10,30]}

' ── Exists ──
' JsonExists — check if path exists
json = "{""user"":{""name"":""Imran""}}"
If m_lv.JsonExists(json, "user.name") Then Debug.Print "Found"
If Not m_lv.JsonExists(json, "user.email") Then
    json = m_lv.JsonSetValue(json, "user.email", "imran@example.com")
End If

' ── Append / Insert ──
' JsonAppend — push to end of array (auto-creates if missing)
json = "{""tags"":[]}"
json = m_lv.JsonAppend(json, "tags", "vba")
json = m_lv.JsonAppend(json, "tags", "com")
' {"tags":["vba","com"]}

' JsonInsert — insert at specific position
json = "[""a"",""c"",""d""]"
json = m_lv.JsonInsert(json, "", 1, "b")
' ["a","b","c","d"]

' ── Merge ──
' JsonMerge — combine two objects
Dim base As String, overlay As String
base = "{""name"":""Imran"",""settings"":{""theme"":""dark"",""lang"":""en""}}"
overlay = "{""age"":30,""settings"":{""theme"":""light""}}"

' Shallow — settings completely replaced
json = m_lv.JsonMerge(base, overlay, False)

' Deep — settings.theme updated, settings.lang preserved
json = m_lv.JsonMerge(base, overlay, True)

' ── Count / Clear ──
' JsonCount — count keys (object) or elements (array)
Dim n As Long
n = m_lv.JsonCount("{""a"":1,""b"":2,""c"":3}", "")  ' 3
n = m_lv.JsonCount("{""items"":[10,20,30]}", "items")  ' 3

' JsonClear — empty a container
json = "{""cache"":{""a"":1},""tags"":[""x""]}"
json = m_lv.JsonClear(json, "cache")   ' cache becomes {}
json = m_lv.JsonClear(json, "tags")    ' tags becomes []

' ── Pretty Print ──
' JsonPrettyPrint — format for debugging (max 5 MB)
Debug.Print m_lv.JsonPrettyPrint("{""name"":""Imran"",""scores"":[95,88]}")

' ── Flatten / Unflatten ──
' JsonFlatten — nested to dot-notation
Dim flat As String
flat = m_lv.JsonFlatten("{""user"":{""name"":""Imran"",""address"":{""city"":""London""}}}")
' {"user.name":"Imran","user.address.city":"London"}

' JsonUnflatten — dot-notation back to nested
Dim nested As String
nested = m_lv.JsonUnflatten(flat)
' {"user":{"name":"Imran","address":{"city":"London"}}}

' ── JsonToRowArray — JSON array → 2D VBA array ──
' Row 1 = headers, Rows 2+ = typed data, 1-based indexing
json = "[{""name"":""Imran"",""age"":30},{""name"":""Ali"",""age"":25,""city"":""London""}]"
Dim arr As Variant
arr = m_lv.JsonToRowArray(json)
' arr(1,1)="name"  arr(1,2)="age"  arr(1,3)="city"    ← headers
' arr(2,1)="Imran" arr(2,2)=30     arr(2,3)=Null       ← row 1
' arr(3,1)="Ali"   arr(3,2)=25     arr(3,3)="London"   ← row 2

' Paste into Excel range
' ws.Range("A1").Resize(UBound(arr,1), UBound(arr,2)).Value = arr

' ── Unwrap ──
' JsonUnwrapString — fix double-encoded string from ExecuteScriptWithResult
Dim raw As String, ok As Boolean, errMsg As String
m_lv.ExecuteScriptWithResult "document.body.dataset.config", raw, ok, errMsg
' raw = """{\""name\"":\""Apple\""}"""  (double-encoded by WebView2)
Dim clean As String
clean = m_lv.JsonUnwrapString(raw)
' clean = "{""name"":""Apple""}"        (usable JSON)
Debug.Print m_lv.JsonGetValue(clean, "name")  ' "Apple"

' ── Compact ──
' JsonCompact — remove null entries from padded arrays
Dim padded As String
padded = "[null,null,{""id"":1},null,{""id"":2}]"
Debug.Print m_lv.JsonCompact(padded, "")
' → [{"id":1},{"id":2}]

' Path-based compact — only compact array inside nested object
Dim nested As String
nested = "{""data"":[null,{""v"":1},null,{""v"":2}]}"
Debug.Print m_lv.JsonCompact(nested, "data")
' → {"data":[{"v":1},{"v":2}]}

JsonToRowArray — Type Mapping

JSON TypeVBA TypeExample
StringString"hello""hello"
IntegerLong4242
DecimalDouble3.143.14
BooleanBooleantrueTrue
NullNullnullNull
Object / ArrayString (raw JSON){"a":1}"{""a"":1}"
Missing keyNull(key absent) → Null

Limits: Max 100,000 rows, 1,000 columns. Input size limited by JsonToArrayMaxSize (default 50 MB).

DOM Manipulation 24 methods

Get and set element values, attributes, and HTML content without writing JavaScript.

MemberParametersReturnsDescription
GetElementValueByIdelementId As StringStringGet element value by ID
SetElementValueByIdelementId As String, value As StringSet element value by ID
GetElementValueByNameelementName As StringStringGet element value by name
SetElementValueByNameelementName As String, value As StringSet element value by name
ClickElementByIdelementId As StringClick element by ID
ClickElementByNameelementName As StringClick element by name
ClickElementBySelectorcssSelector As StringClick element by CSS selector
GetInnerHtmlByIdelementId As StringStringGet innerHTML
SetInnerHtmlByIdelementId As String, html As StringSet innerHTML
GetOuterHtmlByIdelementId As StringStringGet outerHTML
SetOuterHtmlByIdelementId As String, html As StringSet outerHTML
GetOuterHtmlByNameelementName As StringStringGet outerHTML by name
SetOuterHtmlByNameelementName As String, html As StringSet outerHTML by name
GetPageHtmlStringGet complete page HTML
GetPageTextStringGet page text (no tags)
ElementExistsByIdelementId As StringBooleanCheck if element exists
ElementExistsBySelectorcssSelector As StringBooleanCheck if element exists by selector
GetElementTextByIdelementId As StringStringGet text content (not HTML)
SetElementTextByIdelementId As String, text As StringSet text content
GetElementAttributeByIdelementId, attrName As StringStringGet attribute value
SetElementAttributeByIdelementId, attrName, value As StringSet attribute value
RemoveElementAttributeByIdelementId, attrName As StringRemove attribute
FocusElementByIdelementId As StringFocus element
ScrollToElementByIdelementId As StringScroll element into view

Per-Member Usage

' ── Get/Set Values ──
' GetElementValueById / SetElementValueById — by element id
m_lv.SetElementValueById "firstName", "John"
Dim val As String: val = m_lv.GetElementValueById("firstName")

' GetElementValueByName / SetElementValueByName — by name attribute
m_lv.SetElementValueByName "address", "123 Main St"
val = m_lv.GetElementValueByName("address")

' ── Click ──
' ClickElementById — click by id
m_lv.ClickElementById "submitBtn"

' ClickElementByName — click by name attribute
m_lv.ClickElementByName "resetButton"

' ClickElementBySelector — click by CSS selector
m_lv.ClickElementBySelector "form#regForm button[type='submit']"

' ── innerHTML / outerHTML ──
' GetInnerHtmlById / SetInnerHtmlById
Dim inner As String: inner = m_lv.GetInnerHtmlById("header")
m_lv.SetInnerHtmlById "header", "<strong>Updated!</strong>"

' GetOuterHtmlById / SetOuterHtmlById
Dim outer As String: outer = m_lv.GetOuterHtmlById("myDiv")
m_lv.SetOuterHtmlById "myDiv", "<div id='myDiv' class='new'>Replaced</div>"

' GetOuterHtmlByName / SetOuterHtmlByName
outer = m_lv.GetOuterHtmlByName("address")
m_lv.SetOuterHtmlByName "address", "<input name='address' value='New'>"

' ── Page Content ──
' GetPageHtml — full page HTML
Dim html As String: html = m_lv.GetPageHtml

' GetPageText — text only (no tags)
Dim txt As String: txt = m_lv.GetPageText

' ── Existence Checks ──
' ElementExistsById
If m_lv.ElementExistsById("loginForm") Then Debug.Print "Found"

' ElementExistsBySelector
If m_lv.ElementExistsBySelector("div.error-message") Then Debug.Print "Error visible"

' ── Text Content ──
' GetElementTextById / SetElementTextById — textContent (not HTML)
Dim t As String: t = m_lv.GetElementTextById("heading")
m_lv.SetElementTextById "heading", "New Heading Text"

' ── Attributes ──
' GetElementAttributeById
Dim attrVal As String: attrVal = m_lv.GetElementAttributeById("email", "placeholder")

' SetElementAttributeById
m_lv.SetElementAttributeById "email", "style", "border-color: green;"

' RemoveElementAttributeById
m_lv.RemoveElementAttributeById "email", "disabled"

' ── Focus / Scroll ──
' FocusElementById
m_lv.FocusElementById "email"

' ScrollToElementById — scroll element into view
m_lv.ScrollToElementById "footer"
Form Automation 5 methods

High-level form helpers for checkboxes, dropdowns, and form submission.

MemberParametersReturnsDescription
SubmitFormByIdformId As StringSubmit form
SetCheckboxByIdelementId As String, checked As BooleanSet checkbox state
GetCheckboxByIdelementId As StringBooleanGet checkbox state
SelectOptionByIdelementId As String, optionValue As StringSelect dropdown option
GetSelectedOptionByIdelementId As StringStringGet selected option value

Per-Member Usage

' SubmitFormById — submit a <form> by its id
m_lv.SubmitFormById "regForm"

' SetCheckboxById — set checkbox checked/unchecked
m_lv.SetCheckboxById "agreeTerms", True

' GetCheckboxById — read checkbox state
Dim agreed As Boolean
agreed = m_lv.GetCheckboxById("agreeTerms")  ' True / False

' SelectOptionById — select <option> in a <select> dropdown
m_lv.SelectOptionById "country", "us"

' GetSelectedOptionById — read selected option value
Dim country As String
country = m_lv.GetSelectedOptionById("country")  ' "us"
Printing & PDF 6 methods

Print pages, generate PDFs, and capture screenshots.

MemberParametersReturnsDescription
PrintPagePrint to default printer
ShowPrintDialogShow system print dialog
PrintToPdffilePath As StringPrint to PDF file (async, fires PrintToPdfCompleted)
PrintWithSettingsPrint using current print settings
PrintToPdfWithSettingsfilePath As StringPrint to PDF using current print settings
CaptureScreenshotfilePath As StringLongCapture screenshot (fires CaptureScreenshotCompleted)

Per-Member Usage

' PrintPage — send to default printer (no dialog)
m_lv.PrintPage

' ShowPrintDialog — open the system print dialog
m_lv.ShowPrintDialog

' PrintToPdf — export PDF (async, fires PrintToPdfCompleted event)
m_lv.PrintToPdf Environ("USERPROFILE") & "\Desktop\Report.pdf"

' PrintWithSettings — print using current Print Settings properties
m_lv.PrintOrientation = 1  ' Landscape
m_lv.PrintWithSettings

' PrintToPdfWithSettings — PDF with current Print Settings
m_lv.PrintScaleFactor = 0.85
m_lv.PrintToPdfWithSettings "C:\Reports\output.pdf"

' CaptureScreenshot — save page image (fires CaptureScreenshotCompleted)
m_lv.CaptureScreenshot "C:\Screenshots\page.png"
Settings & Configuration 20 properties

Runtime settings that control browser behavior, security, and UI features.

PropertyTypeR/WDescription
IsScriptEnabledBooleanR/WJavaScript enabled
AreDefaultContextMenusEnabledBooleanR/WRight-click menus enabled
AreDevToolsEnabledBooleanR/WDevTools (F12) enabled
IsStatusBarEnabledBooleanR/WStatus bar enabled
ZoomFactorDoubleR/WZoom (1.0 = 100%)
UserAgentStringR/WCustom user agent
IsWebMessageEnabledBooleanR/WWeb messaging enabled
IsBuiltInErrorPageEnabledBooleanR/WBuilt-in error pages
AreBrowserAcceleratorKeysEnabledBooleanR/WCtrl+F, F5, etc.
IsPasswordAutosaveEnabledBooleanR/WPassword autosave
IsGeneralAutofillEnabledBooleanR/WGeneral autofill
IsPinchZoomEnabledBooleanR/WPinch zoom
IsSwipeNavigationEnabledBooleanR/WSwipe navigation
HiddenPdfToolbarItemsLongR/WPDF toolbar flags (see LV2_PDF_TOOLBAR_ITEMS enum)
IsReputationCheckingRequiredBooleanR/WSmartScreen reputation checking
NonClientRegionSupportEnabledBooleanR/WCustom title bar support
DefaultScriptDialogsEnabledBooleanR/Walert/confirm/prompt dialogs
IsZoomControlEnabledBooleanR/WCtrl+scroll zoom
IsDragDropEnabledBooleanWDrag and drop
SmartResizeBooleanR/WAuto-fit on resize (default True)

Per-Member Usage

' IsScriptEnabled — enable/disable JavaScript
m_lv.IsScriptEnabled = True

' AreDefaultContextMenusEnabled — right-click menus
m_lv.AreDefaultContextMenusEnabled = False   ' disable right-click

' AreDevToolsEnabled — F12 DevTools
m_lv.AreDevToolsEnabled = False              ' disable F12

' IsStatusBarEnabled — link preview on hover
m_lv.IsStatusBarEnabled = True

' ZoomFactor — zoom level (1.0 = 100%)
m_lv.ZoomFactor = 1.25                       ' 125%

' UserAgent — custom user agent string
m_lv.UserAgent = "MyApp/1.0 (LiteView2)"

' IsWebMessageEnabled — chrome.webview.postMessage
m_lv.IsWebMessageEnabled = True

' IsBuiltInErrorPageEnabled — browser error pages
m_lv.IsBuiltInErrorPageEnabled = False      ' show custom errors

' AreBrowserAcceleratorKeysEnabled — Ctrl+F, F5, etc.
m_lv.AreBrowserAcceleratorKeysEnabled = False ' disable browser shortcuts

' IsPasswordAutosaveEnabled — password save prompts
m_lv.IsPasswordAutosaveEnabled = False

' IsGeneralAutofillEnabled — form autofill
m_lv.IsGeneralAutofillEnabled = False

' IsPinchZoomEnabled — touch pinch zoom
m_lv.IsPinchZoomEnabled = True

' IsSwipeNavigationEnabled — swipe back/forward
m_lv.IsSwipeNavigationEnabled = False

' HiddenPdfToolbarItems — hide PDF toolbar buttons (flags)
m_lv.HiddenPdfToolbarItems = 0              ' show all

' IsReputationCheckingRequired — SmartScreen
m_lv.IsReputationCheckingRequired = True

' NonClientRegionSupportEnabled — custom title bar
m_lv.NonClientRegionSupportEnabled = False

' DefaultScriptDialogsEnabled — alert/confirm/prompt
m_lv.DefaultScriptDialogsEnabled = True

' IsZoomControlEnabled — Ctrl+scroll zoom
m_lv.IsZoomControlEnabled = True

' IsDragDropEnabled — drag and drop (write-only)
m_lv.IsDragDropEnabled = False

' SmartResize — auto-fit WebView on resize (default True)
m_lv.SmartResize = True
Pre-Init Properties 10 properties
Warning

These properties must be set BEFORE WebView2 creation (before WebViewReady fires). Setting them after has no effect.

PropertyTypeR/WDescription
AdditionalBrowserArgumentsStringR/We.g. "--disable-gpu"
EnableHardwareAccelerationBooleanR/WGPU acceleration
BrowserExecutableFolderStringR/WFixed-version browser folder
LanguageStringR/WBCP 47 language code
ProxyServerStringR/WProxy address
ProxyBypassListStringR/WBypass list
RequiredMinimumVersionStringR/WMin runtime version
AutoRecoverOnCrashBooleanR/WAuto-recreate on crash
EventsUseHexadecimalBooleanR/WVB6 Int64 workaround
JsonToArrayMaxSizeLongR/WMax JSON size for JsonToArray and JsonToRowArray (default 50 MB). Unlike other pre-init properties, this can be changed at any time.

Per-Member Usage

' All pre-init properties must be set BEFORE WebViewReady fires.
' Typically set in Form_Load or Form_Open.

' AdditionalBrowserArguments — pass Chromium command-line flags
m_lv.AdditionalBrowserArguments = "--disable-gpu --disable-extensions"

' EnableHardwareAcceleration — GPU rendering
m_lv.EnableHardwareAcceleration = True

' BrowserExecutableFolder — use fixed-version WebView2 runtime
m_lv.BrowserExecutableFolder = "C:\WebView2Runtime\130.0.2849.80"

' Language — set BCP 47 language code
m_lv.Language = "fr-FR"

' ProxyServer / ProxyBypassList — proxy configuration
m_lv.ProxyServer = "http://proxy.corp.local:8080"
m_lv.ProxyBypassList = "*.local;intranet.corp.local"

' RequiredMinimumVersion — fail if runtime is too old
m_lv.RequiredMinimumVersion = "120.0.0.0"

' AutoRecoverOnCrash — auto-recreate WebView on crash
m_lv.AutoRecoverOnCrash = True

' EventsUseHexadecimal — VB6 workaround for Int64 event params
m_lv.EventsUseHexadecimal = True  ' sends Long params as hex strings

' JsonToArrayMaxSize — max JSON parse size for JsonToArray
m_lv.JsonToArrayMaxSize = 104857600  ' 100 MB
Version & Diagnostics 5 members

Version information and diagnostic utilities.

MemberType / ParametersReturnsDescription
ControlVersionString ROCX version (e.g. "1.0.0.1")
BrowserVersionStringString RWebView2 runtime version
UserDataFolderString RUser data folder path
GetDiagnostics(method)StringDiagnostic info JSON
GetDefaultOcxPath(method)StringDefault OCX path for current Office app

Per-Member Usage

' ControlVersion (R) — OCX version string
Debug.Print "OCX: " & m_lv.ControlVersion       ' "1.0.0.1"

' BrowserVersionString (R) — WebView2 runtime version
Debug.Print "Runtime: " & m_lv.BrowserVersionString ' "130.0.2849.80"

' UserDataFolder (R) — browser data folder path
Debug.Print "Data: " & m_lv.UserDataFolder

' GetDiagnostics — full diagnostic info as JSON
Dim diag As String
diag = m_lv.GetDiagnostics  ' JSON with version, paths, settings, etc.

' GetDefaultOcxPath — default OCX registration path for current Office app
Debug.Print "OCX path: " & m_lv.GetDefaultOcxPath
Host Object Bridge 4 members

Expose COM objects to JavaScript for direct automation from the page.

MemberParametersReturnsDescription
AddHostObjectToScriptname As String, object As ObjectExpose COM object to JS
RemoveHostObjectToScriptname As StringRemove host object
RemoveHostObjectFromScriptname As StringRemove host object (alias)
AreHostObjectsAllowedBoolean R/WMust be True for AddHostObjectToScript

Per-Member Usage

' AreHostObjectsAllowed (R/W) — must be True for host objects to work
Debug.Print "Host objects: " & m_lv.AreHostObjectsAllowed

' AddHostObjectToScript — expose COM object to JS
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "greeting", "Hello from VBA"
m_lv.AddHostObjectToScript "vbaHelper", dict
' JS: let obj = await chrome.webview.hostObjects.vbaHelper

' RemoveHostObjectToScript — remove host object (original name)
m_lv.RemoveHostObjectToScript "vbaHelper"

' RemoveHostObjectFromScript — remove host object (alias, same effect)
m_lv.RemoveHostObjectFromScript "vbaHelper"
Web Message Callback 2 methods

Route JS messages to a VBA macro in a standard module instead of using OCX events.

MemberParametersReturnsDescription
SetWebMessageCallbackvbaApplication As Object, macroName As StringRegister VBA macro for JS messages
ClearWebMessageCallbackClear callback

Per-Member Usage

' SetWebMessageCallback — route JS messages to a VBA macro (standard module)
m_lv.SetWebMessageCallback Application, "OnWebMessage"
' In a standard module:
' Public Sub OnWebMessage(ByVal message As String)
'     Debug.Print "Received: " & message
' End Sub

' ClearWebMessageCallback — stop routing to macro
m_lv.ClearWebMessageCallback
Cookies & Storage 7 methods

Manage browser cache, cookies, and browsing data.

MemberParametersReturnsDescription
ClearCacheClear browser cache
ClearCookiesClear all cookies
ClearBrowsingDatadataKinds As LongClear data by kind flags (see LiteView2BrowsingDataKinds enum)
GetCookiesurl As StringString (JSON)Get cookies for URL
SetCookiename, value, domain, path As StringSet a cookie
ClearProfileCookiesClear profile cookies
ClearBrowsingDataInTimeRangedataKinds As Long, startTime As Date, endTime As DateClear data in time range

Per-Member Usage

' ClearCache — clear browser cache
m_lv.ClearCache

' ClearCookies — clear all cookies
m_lv.ClearCookies

' ClearBrowsingData — clear by kind flags (bitwise OR)
m_lv.ClearBrowsingData 1 + 2 + 4  ' see LiteView2BrowsingDataKinds enum

' GetCookies — get cookies for URL (returns JSON)
Dim cookies As String
cookies = m_lv.GetCookies("https://lv2.local/")

' SetCookie — set a cookie (name, value, domain, path)
m_lv.SetCookie "session_id", "abc123", "lv2.local", "/"

' ClearProfileCookies — clear profile-level cookies
m_lv.ClearProfileCookies

' ClearBrowsingDataInTimeRange — clear data within date range
m_lv.ClearBrowsingDataInTimeRange 1, DateAdd("d", -7, Now()), Now()
Authentication & Proxy 5 members

Configure HTTP authentication, SSL handling, and single sign-on.

MemberParametersReturnsDescription
SetBasicAuthCredentialsuriPattern, username, password As StringSet HTTP Basic Auth
ClearBasicAuthCredentialsClear stored auth
IgnoreCertificateErrorsBoolean R/WIgnore SSL errors
AllowSingleSignOnUsingOSPrimaryAccountBoolean R/WSSO using OS account
HasAuthenticationSupportBoolean REnhanced auth available

Per-Member Usage

' SetBasicAuthCredentials — auto-respond to HTTP Basic Auth challenges
m_lv.SetBasicAuthCredentials "*", "admin", "password123"
' uriPattern: "*" = all, "*.corp.local" = specific domain

' ClearBasicAuthCredentials — remove stored auth
m_lv.ClearBasicAuthCredentials

' IgnoreCertificateErrors (R/W) — skip SSL validation
m_lv.IgnoreCertificateErrors = True   ' for self-signed certs

' AllowSingleSignOnUsingOSPrimaryAccount (R/W) — Windows SSO
m_lv.AllowSingleSignOnUsingOSPrimaryAccount = True

' HasAuthenticationSupport (R) — enhanced auth available
If m_lv.HasAuthenticationSupport Then
    m_lv.SetBasicAuthCredentials "*.corp.local", "user", "pass"
End If
Web Resource Interception 11 members

Intercept, filter, and block web requests. Create custom requests and responses.

MemberParametersReturnsDescription
AddWebResourceRequestedFilteruriPattern As String, resourceContext As LongAdd request filter
RemoveWebResourceRequestedFilteruriPattern As String, resourceContext As LongRemove filter
ClearAllWebResourceRequestedFiltersRemove all filters
GetWebResourceRequestedFiltersString (JSON)Get active filters
SetWebResourceBlockingenabled As BooleanEnable/disable blocking
IsWebResourceBlockingEnabledBoolean RIs blocking on
BlockedRequestCountLong RBlocked requests since reset
ResetBlockedRequestCountReset counter
EnableWebResourceResponseTrackingenabled As BooleanEnable response events
CreateWebResourceRequestmethod, uri, headers, body As StringLongCreate request handle
CreateWebResourceResponsecontent As String, statusCode As Long, reasonPhrase, headers As StringLongCreate response handle

Per-Member Usage

' AddWebResourceRequestedFilter — subscribe to requests matching pattern
m_lv.AddWebResourceRequestedFilter "*://ads.example.com/*", 0  ' 0=All

' RemoveWebResourceRequestedFilter — unsubscribe
m_lv.RemoveWebResourceRequestedFilter "*://ads.example.com/*", 0

' ClearAllWebResourceRequestedFilters — remove all filters
m_lv.ClearAllWebResourceRequestedFilters

' GetWebResourceRequestedFilters — list active filters (JSON)
Dim filters As String
filters = m_lv.GetWebResourceRequestedFilters

' SetWebResourceBlocking — enable/disable blocking mode
m_lv.SetWebResourceBlocking True

' IsWebResourceBlockingEnabled (R) — check if blocking is on
Debug.Print "Blocking: " & m_lv.IsWebResourceBlockingEnabled

' BlockedRequestCount (R) — count of blocked requests
Debug.Print "Blocked: " & m_lv.BlockedRequestCount

' ResetBlockedRequestCount — reset counter to 0
m_lv.ResetBlockedRequestCount

' EnableWebResourceResponseTracking — enable WebResourceResponseReceived events
m_lv.EnableWebResourceResponseTracking True

' CreateWebResourceRequest — create a custom HTTP request handle
Dim hReq As Long
hReq = m_lv.CreateWebResourceRequest("POST", "https://api.example.com", _
    "Content-Type: application/json", "{""data"":1}")

' CreateWebResourceResponse — create a custom HTTP response handle
Dim hResp As Long
hResp = m_lv.CreateWebResourceResponse("<h1>Blocked</h1>", 403, _
    "Forbidden", "Content-Type: text/html")
Downloads 13 members

Control file downloads, download dialog position, and silent download mode.

MemberType / ParametersR/W or ReturnsDescription
DefaultDownloadFolderPathStringR/WDownload folder
AllowDownloadsBooleanR/WAllow downloads
IsDownloadDialogOpenBooleanRDialog state
OpenDownloadDialog(method)Open dialog
CloseDownloadDialog(method)Close dialog
PauseDownloaddownloadId As LongPause download
ResumeDownloaddownloadId As LongResume download
CancelDownloaddownloadId As LongCancel download
ShowSaveAsDialog(method)Show Save As
HiddenDownloadUIBooleanR/WSilent downloads
DefaultDownloadDialogCornerAlignmentLV2_DOWNLOAD_DIALOG_CORNER_ALIGNMENTR/WDialog position
DefaultDownloadDialogMarginXLongR/WDialog margin X
DefaultDownloadDialogMarginYLongR/WDialog margin Y

Per-Member Usage

' DefaultDownloadFolderPath (R/W) — set/get download folder
m_lv.DefaultDownloadFolderPath = "C:\Downloads"
Debug.Print m_lv.DefaultDownloadFolderPath

' AllowDownloads (R/W) — enable/disable downloads
m_lv.AllowDownloads = True

' IsDownloadDialogOpen (R) — check dialog state
Debug.Print "Dialog open: " & m_lv.IsDownloadDialogOpen

' OpenDownloadDialog / CloseDownloadDialog
m_lv.OpenDownloadDialog
m_lv.CloseDownloadDialog

' PauseDownload — pause by download ID
m_lv.PauseDownload m_lastDownloadId

' ResumeDownload — resume paused download
m_lv.ResumeDownload m_lastDownloadId

' CancelDownload — cancel download
m_lv.CancelDownload m_lastDownloadId

' ShowSaveAsDialog — prompt user for save location
m_lv.ShowSaveAsDialog

' HiddenDownloadUI (R/W) — silent downloads (no UI)
m_lv.HiddenDownloadUI = True

' DefaultDownloadDialogCornerAlignment (R/W) — dialog position
m_lv.DefaultDownloadDialogCornerAlignment = 0  ' see LV2_DOWNLOAD_DIALOG_CORNER_ALIGNMENT

' DefaultDownloadDialogMarginX / MarginY (R/W) — dialog offset
m_lv.DefaultDownloadDialogMarginX = 20
m_lv.DefaultDownloadDialogMarginY = 20
Find in Page 9 members

Programmatic find-in-page with match counting and navigation.

MemberParametersReturnsDescription
StartFindsearchText As String, caseSensitive As Boolean, matchWholeWord As BooleanStart finding
FindNextNext match
FindPreviousPrevious match
StopFindcancel As BooleanStop finding
FindMatchCountLong RTotal matches
FindActiveMatchIndexLong RCurrent match (1-based)
IsFindActiveBoolean RSession active
SuppressFindUIBoolean R/WHide default Find UI
FindHighlightAllMatchesBoolean R/WHighlight all

Per-Member Usage

' StartFind — begin a find session (text, caseSensitive, matchWholeWord)
m_lv.StartFind "webview2", False, False

' FindNext — go to next match
m_lv.FindNext

' FindPrevious — go to previous match
m_lv.FindPrevious

' StopFind — end session (True=clear highlights, False=keep last highlight)
m_lv.StopFind True

' FindMatchCount (R) — total matches found
Debug.Print "Matches: " & m_lv.FindMatchCount

' FindActiveMatchIndex (R) — current match index (1-based)
Debug.Print "Current: " & m_lv.FindActiveMatchIndex

' IsFindActive (R) — True if a find session is running
If m_lv.IsFindActive Then m_lv.StopFind True

' SuppressFindUI (R/W) — hide the default browser Find bar
m_lv.SuppressFindUI = True   ' use your own UI instead

' FindHighlightAllMatches (R/W) — highlight all matches at once
m_lv.FindHighlightAllMatches = True
Lifecycle & Resources 11 members

Suspend, resume, and manage WebView2 memory and lifecycle.

MemberParametersReturnsDescription
TrySuspendSuspend WebView to reduce resources
ResumeResume after suspend
IsSuspendedBoolean RCheck if suspended
GetMemoryUsageLongApproximate memory in bytes
ForceGarbageCollectionForce JS GC
DisposeRelease all WebView resources
CloseBrowserProcessForce close browser
IsVisibleBoolean R/WVisibility state
MemoryUsageTargetLevelLong R/W0=Normal, 1=Low
MoveFocusreason As LongMove focus in/out of WebView
NotifyParentWindowPositionChangedFix DPI/rendering after move

Per-Member Usage

' TrySuspend — suspend WebView to reduce resource usage
m_lv.TrySuspend

' Resume — resume after suspend
m_lv.Resume

' IsSuspended (R) — check if suspended
If m_lv.IsSuspended Then m_lv.Resume

' GetMemoryUsage — approximate memory in bytes
Debug.Print "Memory: " & Format(m_lv.GetMemoryUsage / 1048576, "0.0") & " MB"

' ForceGarbageCollection — trigger JS garbage collection
m_lv.ForceGarbageCollection

' Dispose — release all WebView2 resources (cannot be undone)
m_lv.Dispose

' CloseBrowserProcess — force-close the browser subprocess
m_lv.CloseBrowserProcess

' IsVisible (R/W) — show/hide the WebView
m_lv.IsVisible = False   ' hide browser while loading
m_lv.IsVisible = True    ' show when ready

' MemoryUsageTargetLevel (R/W) — 0=Normal, 1=Low
m_lv.MemoryUsageTargetLevel = 1  ' reduce memory footprint

' MoveFocus — move focus in/out of WebView
m_lv.MoveFocus 0  ' 0=Next, 1=Previous, 2=Programmatic

' NotifyParentWindowPositionChanged — fix DPI/rendering after move
m_lv.NotifyParentWindowPositionChanged
Privacy & Compatibility 9 members

Browser privacy controls and compatibility settings for enterprise and testing environments.

MemberParametersReturnsDescription
EnableStealthModeenabled As BooleanEnable comprehensive privacy protection mode
HideWebDriverhide As BooleanRemove automation indicators for browser compatibility
SpoofWebGLvendor As String, renderer As StringSet custom WebGL renderer strings for compatibility testing
RandomizeCanvasFingerprintenabled As BooleanProtect against cross-site canvas fingerprint tracking
SpoofScreenSizewidth As Long, height As Long, colorDepth As LongSet custom screen dimensions for responsive testing
DisableWebRTCdisabled As BooleanPrevent WebRTC IP address exposure for privacy
EnableMouseNoiseenabled As BooleanNatural mouse movement simulation for UI testing
EnableTimingNoiseminMs As Long, maxMs As LongRandomized timing for realistic interaction testing
IsStealthEnabledBoolean RCheck if privacy mode is active

Per-Member Usage

' EnableStealthMode — comprehensive privacy protection
m_lv.EnableStealthMode True

' HideWebDriver — remove navigator.webdriver indicator
m_lv.HideWebDriver True

' SpoofWebGL — custom WebGL renderer strings
m_lv.SpoofWebGL "NVIDIA Corporation", "NVIDIA GeForce RTX 4090"

' RandomizeCanvasFingerprint — protect against canvas tracking
m_lv.RandomizeCanvasFingerprint True

' SpoofScreenSize — custom screen dimensions for responsive testing
m_lv.SpoofScreenSize 1920, 1080, 24  ' width, height, colorDepth

' DisableWebRTC — prevent IP address exposure
m_lv.DisableWebRTC True

' EnableMouseNoise — natural mouse movement simulation
m_lv.EnableMouseNoise True

' EnableTimingNoise — randomized timing for realistic interactions
m_lv.EnableTimingNoise 50, 200  ' minMs, maxMs

' IsStealthEnabled (R) — check if privacy mode is active
Debug.Print "Stealth: " & m_lv.IsStealthEnabled
CAPTCHA Handling 6 methods

Tools for handling CAPTCHA challenges in automated testing and QA workflows.

MemberParametersReturnsDescription
SetCaptchaServiceserviceName As String, apiKey As StringConfigure CAPTCHA solving service for automated testing
DetectCaptchaStringDetect CAPTCHA presence on page (returns JSON)
SolveCaptchatimeoutMs As LongBooleanResolve detected CAPTCHA challenge
SolveRecaptchaV2siteKey As String, pageUrl As StringStringHandle reCAPTCHA v2 challenge
SolveHCaptchasiteKey As String, pageUrl As StringStringHandle hCaptcha challenge
SubmitCaptchaTokentoken As StringSubmit resolved token to page

Per-Member Usage

' SetCaptchaService — configure solving service (e.g. 2captcha)
m_lv.SetCaptchaService "2captcha", "YOUR_API_KEY"

' DetectCaptcha — check if page has a CAPTCHA (returns JSON)
Dim info As String
info = m_lv.DetectCaptcha  ' e.g. '{"type":"recaptcha_v2","siteKey":"..."}'

' SolveCaptcha — resolve detected CAPTCHA (timeout in ms)
Dim solved As Boolean
solved = m_lv.SolveCaptcha(30000)

' SolveRecaptchaV2 — handle reCAPTCHA v2 specifically
Dim token As String
token = m_lv.SolveRecaptchaV2("6Le-SITE-KEY", "https://example.com/login")

' SolveHCaptcha — handle hCaptcha specifically
token = m_lv.SolveHCaptcha("HCAPTCHA-SITE-KEY", "https://example.com/login")

' SubmitCaptchaToken — inject resolved token into page
m_lv.SubmitCaptchaToken token
Automation API 3 methods
Playwright-Style Helpers

High-level automation methods that simplify common patterns. WaitForElement polls every 50 ms using ElementExistsBySelector — the UI stays responsive (messages are pumped between checks). All methods accept CSS selectors.

MemberParametersReturnsDescription
WaitForElementcssSelector As String, timeoutMs As LongBooleanWait for element matching CSS selector to appear in DOM. Returns True if found, False on timeout. Polls every 50 ms.
ClickElementBySelectorcssSelector As StringClick the first element matching CSS selector.
GetTextBySelectorcssSelector As StringStringGet textContent of first element matching CSS selector.
Timeout Behaviour

WaitForElement checks immediately first — if the element already exists, it returns instantly. Otherwise it polls every 50 ms, pumping messages between checks so the UI stays responsive. If timeoutMs is 0 or omitted, the SynchronousTimeOut property value is used (default 30 s).

Usage — Login Automation Example

' Navigate and wait for login form to appear
m_lv.Navigate "https://example.com/login"

' Wait up to 10 seconds for the form element
If m_lv.WaitForElement("#loginForm", 10000) Then
    ' Fill fields (use existing SetElementValueById or selector methods)
    m_lv.SetElementValueById "email", "user@example.com"
    m_lv.SetElementValueById "password", "secret123"

    ' Click submit button by CSS selector
    m_lv.ClickElementBySelector "#loginForm button[type='submit']"

    ' Wait for dashboard to render
    If m_lv.WaitForElement(".dashboard-panel", 15000) Then
        ' Read welcome message
        Dim welcome As String
        welcome = m_lv.GetTextBySelector(".welcome-message")
        Debug.Print "Logged in: " & welcome
    End If
Else
    Debug.Print "Login form did not appear within 10 seconds"
End If

Reg-Free (BrowserPool) Usage

' Same methods, with browserIndex as first parameter
If m_Pool.WaitForElement(m_Idx, "#dashboard", 10000) Then
    Dim msg As String
    msg = m_Pool.GetTextBySelector(m_Idx, ".status-text")
End If
Embedding 7 methods

Embed the WebView2 browser in external window handles (HWND) or Access Frames.

MemberParametersReturnsDescription
EmbedInHwndhwndParent As LongLong, width As Long, height As LongEmbed in external HWND (64-bit VBA only — use EmbedInHwndByLong for 32-bit)
EmbedInHwndByLonghwndParent As Long, width As Long, height As LongVB6/VFP compatibility
ResizeEmbeddedwidth As Long, height As LongResize embedded browser
MoveEmbeddedleft As Long, top As LongReposition embedded browser
CloseEmbeddedDestroy embedded browser
QuickInitInFrameparentForm As Object, targetFrame As ObjectAuto DPI/handle init in Frame
PointsToPixelspoints As Long, isHorizontal As BooleanLongDPI conversion

Per-Member Usage

' EmbedInHwnd — embed WebView2 in an external window handle
m_lv.EmbedInHwnd hwndParent, 800, 600

' EmbedInHwndByLong — VB6/VFP compatibility version
m_lv.EmbedInHwndByLong hwndParent, 800, 600

' ResizeEmbedded — resize embedded browser
m_lv.ResizeEmbedded 1024, 768

' MoveEmbedded — reposition embedded browser
m_lv.MoveEmbedded 10, 50   ' left, top in pixels

' CloseEmbedded — destroy embedded browser instance
m_lv.CloseEmbedded

' QuickInitInFrame — auto DPI/handle init inside an Access Frame control
m_lv.QuickInitInFrame Me, Me.Frame1

' PointsToPixels — convert Access twips/points to screen pixels
Dim px As Long
px = m_lv.PointsToPixels(400, True)  ' horizontal DPI conversion
Document Hosting 16 members

Open, edit, and preview documents (Office, PDF, images, video) inside the WebView2 control.

MemberParametersReturnsDescription
OpenDocumentfilePath As String, viewMode As LongOpen any document. viewMode: 0=Auto, 1=ForceHTML, 2=ForcePDF
OpenOfficeDocumentfilePath As StringOpen Office doc for editing
CloseOfficeDocumentClose embedded Office doc
SaveOfficeDocumentSave
SaveOfficeDocumentAsfilePath As StringSave As
IsOfficeDocumentOpenBoolean RIs doc open
OfficeDocumentPathString RCurrent doc path
OfficeDocumentTypeString RWord/Excel/PowerPoint/Unknown
CurrentDocumentPathString RCurrent doc path (universal)
CurrentDocumentTypeString RImage/PDF/Video/Audio/Text/Word/Excel/PowerPoint
WordApplicationObject RWord.Application for automation
WordDocumentObject RActive Word.Document
ShowDocumentPreviewfilePath As String, hwndTarget As LongPtrPreview in separate window
ShowDocumentPreviewInBrowserFramefilePath As StringPreview in same Frame as WebView2
CloseDocumentPreviewClose preview
EmbeddedParentHwndLongPtr RFrame window handle

Per-Member Usage

' OpenDocument — open any file (viewMode: 0=Auto, 1=ForceHTML, 2=ForcePDF)
m_lv.OpenDocument "C:\Reports\invoice.pdf", 0

' OpenOfficeDocument — open Word/Excel/PowerPoint for editing
m_lv.OpenOfficeDocument "C:\Docs\template.docx"

' CloseOfficeDocument — close the embedded Office document
m_lv.CloseOfficeDocument

' SaveOfficeDocument — save changes
m_lv.SaveOfficeDocument

' SaveOfficeDocumentAs — save to new path
m_lv.SaveOfficeDocumentAs "C:\Docs\copy.docx"

' IsOfficeDocumentOpen (R) — check if doc is open
If m_lv.IsOfficeDocumentOpen Then m_lv.SaveOfficeDocument

' OfficeDocumentPath (R) — current document path
Debug.Print m_lv.OfficeDocumentPath

' OfficeDocumentType (R) — Word/Excel/PowerPoint/Unknown
Debug.Print m_lv.OfficeDocumentType

' CurrentDocumentPath (R) — universal (any doc type)
Debug.Print m_lv.CurrentDocumentPath

' CurrentDocumentType (R) — Image/PDF/Video/Audio/Text/Word/Excel/etc.
Debug.Print m_lv.CurrentDocumentType

' WordApplication (R) — get Word.Application for automation
Dim wdApp As Object: Set wdApp = m_lv.WordApplication

' WordDocument (R) — get active Word.Document
Dim wdDoc As Object: Set wdDoc = m_lv.WordDocument

' ShowDocumentPreview — preview in external window
m_lv.ShowDocumentPreview "C:\Reports\chart.png", hwndTarget

' ShowDocumentPreviewInBrowserFrame — preview in same frame
m_lv.ShowDocumentPreviewInBrowserFrame "C:\Reports\chart.png"

' CloseDocumentPreview — close preview
m_lv.CloseDocumentPreview

' EmbeddedParentHwnd (R) — frame window handle
Debug.Print "Frame HWND: " & m_lv.EmbeddedParentHwnd
DevTools Protocol 6 members

Access Chrome DevTools Protocol (CDP) for advanced browser automation.

MemberParametersReturnsDescription
OpenDevToolsWindowOpen F12 DevTools
CallDevToolsProtocolMethodmethodName As String, parametersAsJson As StringStringCall CDP method
AddDevToolsProtocolEventHandlereventName As StringSubscribe to CDP event
RemoveDevToolsProtocolEventHandlereventName As StringUnsubscribe
HasDevToolsProtocolBoolean RCDP available
OpenTaskManagerWindowBrowser task manager

Per-Member Usage

' OpenDevToolsWindow — open F12 DevTools
m_lv.OpenDevToolsWindow

' CallDevToolsProtocolMethod — call any CDP method
Dim result As String
result = m_lv.CallDevToolsProtocolMethod("Browser.getVersion", "{}")
result = m_lv.CallDevToolsProtocolMethod("Page.captureScreenshot", "{""format"":""png""}")

' AddDevToolsProtocolEventHandler — subscribe to CDP event
m_lv.AddDevToolsProtocolEventHandler "Page.loadEventFired"

' RemoveDevToolsProtocolEventHandler — unsubscribe
m_lv.RemoveDevToolsProtocolEventHandler "Page.loadEventFired"

' HasDevToolsProtocol (R) — check if CDP is available
If m_lv.HasDevToolsProtocol Then
    result = m_lv.CallDevToolsProtocolMethod("Runtime.evaluate", _
        "{""expression"":""1+1""}")
End If

' OpenTaskManagerWindow — open browser task manager
m_lv.OpenTaskManagerWindow
Profile Settings 7 members

Browser profile preferences including color scheme, tracking prevention, and popup handling.

PropertyTypeR/WDescription
PreferredColorSchemeLV2_COLOR_SCHEMER/WAuto/Light/Dark
PreferredTrackingPreventionLevelLV2_TRACKING_PREVENTIONR/WTracking prevention
ProfileIsPasswordAutosaveEnabledBooleanR/WProfile password save
ProfileIsGeneralAutofillEnabledBooleanR/WProfile autofill
GetBrowserExtensionList(method)String (JSON)Extensions
PopupModeLV2_POPUP_MODER/WPopup handling
OpenPopupsInSameWindowBooleanR/WLegacy popup control

Per-Member Usage

' PreferredColorScheme (R/W) — 0=Auto, 1=Light, 2=Dark
m_lv.PreferredColorScheme = 2  ' force dark mode

' PreferredTrackingPreventionLevel (R/W) — 0=None, 1=Basic, 2=Balanced, 3=Strict
m_lv.PreferredTrackingPreventionLevel = 2

' ProfileIsPasswordAutosaveEnabled (R/W) — profile-level password save
m_lv.ProfileIsPasswordAutosaveEnabled = False

' ProfileIsGeneralAutofillEnabled (R/W) — profile-level autofill
m_lv.ProfileIsGeneralAutofillEnabled = False

' GetBrowserExtensionList — installed extensions (JSON array)
Dim ext As String
ext = m_lv.GetBrowserExtensionList

' PopupMode (R/W) — 0=Allow, 1=BlockAll, 2=SameWindow
m_lv.PopupMode = 1  ' block all popups

' OpenPopupsInSameWindow (R/W) — legacy popup control
m_lv.OpenPopupsInSameWindow = True  ' load popups in same WebView
Licensing 7 members

Query license status and activate product keys.

MemberType / ParametersReturnsDescription
LicenseStatusString RVALID, TRIAL, EXPIRED, UNLICENSED
LicenseTypeString RTRIAL, PRO, ENTERPRISE, NONE
TrialDaysRemainingLong RDays left in trial
LicenseExpiryDate RExpiry date
LicenseVersionString RLicensed version range
LicenseStateLV2_LICENSE_STATE REnum state
ActivateLicensecompany As String, key As StringActivate with HMAC key

Licensing Example

Source: frmAdvancedFeatures_Code.txt

' Check license status
Debug.Print "Status: " & m_lv.LicenseStatus       ' VALID, TRIAL, EXPIRED
Debug.Print "Type:   " & m_lv.LicenseType         ' TRIAL, PRO, ENTERPRISE
Debug.Print "Days:   " & m_lv.TrialDaysRemaining
Debug.Print "State:  " & m_lv.LicenseState        ' LV2_LICENSE_STATE enum

' Activate with license key
m_lv.ActivateLicense "MyCompany", "XXXXX-XXXXX-XXXXX"
Bridge Inspector 1 method

Debug VBA/JS communication with a live message traffic HUD.

MemberParametersReturnsDescription
ToggleBridgeInspectorToggle HUD showing live JS/VBA message traffic

Bridge Inspector Example

Source: frmScriptBridge_Code.txt

' Toggle the live message traffic HUD overlay
m_lv.ToggleBridgeInspector
' A floating panel appears showing all JS/VBA messages in real time
Synchronous Navigation 1 property

Configure timeout for synchronous navigation methods (NavigateSync, NavigateToStringSync).

PropertyTypeR/WDescription
SynchronousTimeOutLongR/WTimeout in ms for NavigateSync etc. (default 30000)

Sync Navigation Example

Source: frmBrowserExplorer_Code.txt

' Set timeout and navigate synchronously (blocks VBA until loaded)
m_lv.SynchronousTimeOut = 15000
m_lv.NavigateSync "https://www.example.com"
' VBA execution resumes here after page fully loads
Debug.Print "Loaded: " & m_lv.Url
Warning

NavigateSync and NavigateToStringSync use a re-entrant message loop that conflicts with Access VBA (COM STA limitation). They work in VB6/VFP but may hang in Access. Use async Navigate + NavigationCompleted event instead.

Explore More:
Core API | Events | JSON | Browser Pool | Enumerations