CDP Guide - Chrome DevTools Protocol Calling Guide
📖 Table of Contents
- Overview
- Synchronous Calls
- Asynchronous Calls
- Common CDP Methods
- Cookie Operations
- Performance and Limitations
- Complete Examples
Overview
Chrome DevTools Protocol (CDP) is a low-level debugging and control protocol provided by the Chromium browser. cWebView2Host enables VB6 to directly call CDP, achieving deep control over browser behavior that far exceeds the capabilities of the WebView2 public API.
✨ Core Features
- 🔧 Sync/Async Dual Mode - Simple scenarios use synchronous calls for results; complex scenarios use async to avoid blocking
- 🍪 HttpOnly Cookies - Access HttpOnly cookies that JavaScript cannot read via CDP
- 📸 Screenshot Capture - Call Page.captureScreenshot for page screenshots
- 🔍 Deep DOM Operations - Directly manipulate DOM tree without going through the JavaScript layer
- 🌐 Network Control - Intercept and modify network requests/responses
Synchronous Calls
CallDevToolsProtocolMethodSync
Blocks the current thread until CDP returns the result — the simplest usage:
Public Function CallDevToolsProtocolMethodSync( _
ByVal MethodName As String, _
ByVal ParametersAsJson As String) As StringReturns: JSON string of CDP response
Internal Mechanism: Uses Sleep + DoEvents loop for waiting, does not affect VB6 form message loop.
Example:
Dim wv As New cWebView2Host ' Synchronous calls don't need WithEvents
Private Sub Form_Load()
wv.Initialize Me.hWnd, "https://vb6.pro"
End Sub
Private Sub Command1_Click()
' Get page title
Dim title As String
title = wv.CallDevToolsProtocolMethodSync( _
"Runtime.evaluate", _
"{""expression"":""document.title""}")
MsgBox "Title: " & title
' Get all cookies
Dim cookies As String
cookies = wv.CallDevToolsProtocolMethodSync( _
"Network.getCookies", _
"{}")
' Get browser version
Dim version As String
version = wv.CallDevToolsProtocolMethodSync( _
"Browser.getVersion", _
"{}")
End SubWhen to Use Synchronous Mode
- Simple query operations (getting properties, cookies, etc.)
- Need to get results immediately for subsequent logic
- Not concerned about UI blocking (or blocking time is very short)
Asynchronous Calls
CallDevToolsProtocolMethod
Initiate CDP call and return immediately; results are returned asynchronously via events:
Public Sub CallDevToolsProtocolMethod( _
ByVal MethodName As String, _
ByVal ParametersAsJson As String, _
ByVal CustomEventId As String)Parameters:
CustomEventId- Custom event ID for matching responses in theDevToolsProtocolResponseevent
Example:
Dim WithEvents wv As cWebView2Host ' Async requires WithEvents
Private Sub Command1_Click()
' Initiate multiple async CDP calls
wv.CallDevToolsProtocolMethod "Page.captureScreenshot", "{}", "screenshot"
wv.CallDevToolsProtocolMethod "DOM.getDocument", "{}", "domDoc"
wv.CallDevToolsProtocolMethod "Runtime.evaluate", _
"{""expression"":""document.URL""}", "pageUrl"
End Sub
Private Sub wv_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String)
Select Case CustomEventId
Case "screenshot"
Debug.Print "Screenshot data received"
' JsonResponse contains base64-encoded screenshot data
Case "domDoc"
Debug.Print "DOM document: " & Left(JsonResponse, 200)
Case "pageUrl"
Debug.Print "Page URL: " & JsonResponse
End Select
End SubWhen to Use Asynchronous Mode
- Time-consuming operations (screenshots, extensive DOM operations)
- Need to initiate multiple CDP calls simultaneously
- Don't want to block the UI thread
Common CDP Methods
Runtime Domain
| Method | Parameters | Purpose |
|---|---|---|
Runtime.evaluate | {expression, returnByValue?, awaitPromise?} | Execute JS expression |
Runtime.callFunctionOn | {functionDeclaration, objectId, arguments, returnByValue} | Call function on specified object |
Runtime.getProperties | {objectId, ownProperties} | Get object properties |
Network Domain
| Method | Parameters | Purpose |
|---|---|---|
Network.getCookies | {urls?} | Get cookies (including HttpOnly) |
Network.getAllCookies | {} | Get all cookies |
Network.deleteCookies | {name, url?, domain?, path?} | Delete cookies |
Network.setCookie | {name, value, url?, domain?, path?, httpOnly?, secure?} | Set cookie |
Network.setExtraHTTPHeaders | {headers} | Set extra HTTP headers |
Page Domain
| Method | Parameters | Purpose |
|---|---|---|
Page.captureScreenshot | {format?, quality?, clip?} | Page screenshot |
Page.printToPDF | {landscape?, paperWidth?, ...} | Print to PDF |
Page.navigate | {url, referrer?} | Navigate |
Page.reload | {ignoreCache?} | Reload |
DOM Domain
| Method | Parameters | Purpose |
|---|---|---|
DOM.getDocument | {depth?} | Get document root node |
DOM.querySelector | {nodeId, selector} | CSS selector query |
DOM.getOuterHTML | {nodeId} | Get element HTML |
DOM.setAttributeValue | {nodeId, name, value} | Set attribute value |
Browser Domain
| Method | Parameters | Purpose |
|---|---|---|
Browser.getVersion | {} | Get browser version info |
Cookie Operations
Simple Mode (cWebView2Cookies)
' document.cookie parsing (excluding HttpOnly)
Dim simple As String
simple = wv.Cookies.GetCookies
' CDP Network.getCookies (including HttpOnly, synchronous)
Dim full As String
full = wv.Cookies.GetCookiesFullFull CDP Cookie Operations
' Get all cookies (with detailed info)
Dim cookies As String
cookies = wv.CallDevToolsProtocolMethodSync("Network.getAllCookies", "{}")
' Return format: {"result":{"cookies":[{name,value,domain,path,httpOnly,secure,...}]}}
' Set cookie
wv.CallDevToolsProtocolMethodSync "Network.setCookie", _
"{""name"":""token"",""value"":""abc123"",""domain"":"".example.com"",""httpOnly"":true}"
' Delete cookie
wv.CallDevToolsProtocolMethodSync "Network.deleteCookies", _
"{""name"":""token"",""domain"":"".example.com""}"Performance and Limitations
Synchronous Call Timeout
CallDevToolsProtocolMethodSync has a default timeout of 5 seconds. For time-consuming CDP operations (e.g., screenshots), use asynchronous mode.
CDP Version Compatibility
CDP method availability depends on the WebView2 Runtime version. Use Browser.getVersion to check the version:
Dim version As String
version = wv.CallDevToolsProtocolMethodSync("Browser.getVersion", "{}")
' Returns fields including product, protocolVersion, etc.Call Frequency
CDP calls are heavier than JS execution — avoid high-frequency calls in loops. For batch operations, prefer single JS execution:
' Avoid: Many CDP calls in a loop
For i = 0 To 100
wv.CallDevToolsProtocolMethodSync "DOM.setAttributeValue", ...
Next
' Recommended: Single JS execution
wv.JsRun "document.querySelectorAll('.item').forEach(el => el.classList.add('active'))"Complete Examples
Page Screenshot
Private Sub Command1_Click()
wv.CallDevToolsProtocolMethod "Page.captureScreenshot", _
"{""format"":""png""}", "screenshot"
End Sub
Private Sub wv_DevToolsProtocolResponse(ByVal CustomEventId As Variant, ByVal JsonResponse As String)
If CustomEventId = "screenshot" Then
' JsonResponse contains base64-encoded PNG data
' Parse and save to file...
Debug.Print "Screenshot received, length: " & Len(JsonResponse)
End If
End SubNetwork Request Interception
' Set extra request headers
wv.CallDevToolsProtocolMethodSync "Network.setExtraHTTPHeaders", _
"{""headers"":{""X-Custom-Header"":""MyValue""}}"Modifying DOM Attributes
' Modify element attribute via CDP
Dim result As String
result = wv.CallDevToolsProtocolMethodSync("Runtime.evaluate", _
"{""expression"":""document.getElementById('title').textContent = 'New Title'""}")Last Updated: 2026-06-24