WebView2 Eval Demo - JavaScript Expression Evaluation
Overview
Demonstrates cWebView2Host's Script.Eval method for synchronously executing JavaScript expressions and getting return values in VB6.
Project Structure
Download Source [ Note: Re-register the DLL file in the bin directory ]
Source code is available in the VBMAN2 project's demos/webview2/eval directory.
eval/
├── Form1.frm # Main form, containing JS evaluation logic
├── pic/
│ └── eval.png # Screenshot of running result
├── vbman2_webview2.vbp # VB6 project file
└── vbman2_webview2.vbw # VB6 workspace fileCore Code Walkthrough
1. Declaration and Initialization (Form1.frm)
vb
Dim wv As New cWebView2Host
Private Sub Form_Load()
wv.Initialize Me.hWnd, "https://vb6.pro"
End Sub2. JavaScript Evaluation
vb
Private Sub GetHtml_Click()
MsgBox wv.Script.Eval("return document.querySelector('.hero-title').innerHTML")
End SubKey features of Script.Eval:
- Use
returnstatement in code to return values - Synchronous execution, directly get return value
- Supports complete JS syntax including DOM operations
Feature Description
Script.Eval Method
- Wraps JS code as a function, then executes it
- Uses
returnto return values to VB6 - Synchronous execution, immediately get results
DOM Queries
- Uses
document.querySelector()to select DOM elements - Read element attributes (innerHTML, textContent, etc.)
- Uses
Technical Notes
Eval vs JsRun differences:
Script.Eval(code)— Wrapped as function, requiresreturnfor valueJsRun(expression)— Directly executes expression, auto-returns result
Must use return: Eval wraps code as
function EvalFuncName(){<code>}, soreturnis needed to pass back valuesError handling: If JS code throws an exception, Eval returns an empty string
Use Cases
- Reading specific element text or attributes from a page
- Executing complex DOM queries
- Evaluating JS expressions (e.g., JSON processing, date formatting)
Extension Suggestions
- Combine Script.Eval and SetData for more flexible data reading
- For simple property reading, prefer
JsProporJsRun - When using Eval for complex multi-line logic, verify in the browser console first