WebView2 CDP Sync Demo - Pure Synchronous CDP Calls
Overview
The CDP Sync demo is a simplified version of the CDP demo, using only synchronous CDP calling mode. Since no event callback handling is needed, the simpler Dim wv As New declaration can be used.
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/cdpSync directory.
cdpSync/
├── Form1.frm # Main form, containing synchronous CDP calls
├── 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 SubNote: Uses Dim wv As New for auto-instantiation; synchronous mode doesn't need WithEvents.
2. Pure Synchronous CDP Calls
vb
Private Sub MenuSendCDP_Click()
' Execute multiple synchronous CDP calls sequentially
Dim sTitle As String
sTitle = wv.CallDevToolsProtocolMethodSync( _
"Runtime.evaluate", _
"{""expression"":""document.title""}")
Debug.Print "[Sync] Title -> " & sTitle
Dim sCookies As String
sCookies = wv.CallDevToolsProtocolMethodSync( _
"Network.getCookies", _
"{}")
Debug.Print "[Sync] Cookies -> " & sCookies
Dim sUrl As String
sUrl = wv.CallDevToolsProtocolMethodSync( _
"Runtime.evaluate", _
"{""expression"":""document.URL""}")
Debug.Print "[Sync] URL -> " & sUrl
Dim sVersion As String
sVersion = wv.CallDevToolsProtocolMethodSync( _
"Browser.getVersion", _
"{}")
Debug.Print "[Sync] Version -> " & sVersion
MsgBox "Title: " & sTitle, vbInformation, "CDP Sync Demo"
End SubFeature Description
Pure Synchronous CDP Calls
- All
CallDevToolsProtocolMethodSynccalls block waiting for results - Return values are directly usable, no event handling required
- All
Simplified Code Structure
- No WithEvents declaration needed
- No event handler functions needed
- Code logic is linear and straightforward
CDP Methods Demonstrated
- Runtime.evaluate: Execute JS and get return value
- Network.getCookies: Get cookie information
- Browser.getVersion: Get browser version
Technical Notes
- Synchronous vs Asynchronous Choice: Synchronous calls are simpler and more direct, but block the current thread. For fast operations (millisecond-level returns), synchronous mode is preferable
- No WithEvents Needed: Synchronous mode doesn't use event callbacks; can use
Dim wv As Newfor simplified declaration - Sequential Execution: Multiple synchronous calls execute in order; each subsequent call starts only after the previous one completes
Use Cases
- Quick retrieval of page information (title, URL, cookies)
- Debugging and diagnostic tools
- Simple CDP integration without time-consuming operations
Extension Suggestions
- If you need time-consuming CDP operations (e.g., screenshots), refer to the cdp demo and switch to async mode
- Commonly used CDP calls can be encapsulated as VB6 helper functions to reduce repetitive code