Skip to content

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 file

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

2. JavaScript Evaluation ​

vb
Private Sub GetHtml_Click()
    MsgBox wv.Script.Eval("return document.querySelector('.hero-title').innerHTML")
End Sub

Key features of Script.Eval:

  • Use return statement in code to return values
  • Synchronous execution, directly get return value
  • Supports complete JS syntax including DOM operations

Feature Description ​

  1. Script.Eval Method

    • Wraps JS code as a function, then executes it
    • Uses return to return values to VB6
    • Synchronous execution, immediately get results
  2. DOM Queries

    • Uses document.querySelector() to select DOM elements
    • Read element attributes (innerHTML, textContent, etc.)

Technical Notes ​

  1. Eval vs JsRun differences:

    • Script.Eval(code) — Wrapped as function, requires return for value
    • JsRun(expression) — Directly executes expression, auto-returns result
  2. Must use return: Eval wraps code as function EvalFuncName(){<code>}, so return is needed to pass back values

  3. Error handling: If JS code throws an exception, Eval returns an empty string

Use Cases ​

  1. Reading specific element text or attributes from a page
  2. Executing complex DOM queries
  3. Evaluating JS expressions (e.g., JSON processing, date formatting)

Extension Suggestions ​

  1. Combine Script.Eval and SetData for more flexible data reading
  2. For simple property reading, prefer JsProp or JsRun
  3. When using Eval for complex multi-line logic, verify in the browser console first

VB6 and LOGO copyright of Microsoft Corporation