Skip to content

CDP Guide - Chrome DevTools Protocol Calling Guide

📖 Table of Contents


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:

vb
Public Function CallDevToolsProtocolMethodSync( _
    ByVal MethodName As String, _
    ByVal ParametersAsJson As String) As String

Returns: JSON string of CDP response

Internal Mechanism: Uses Sleep + DoEvents loop for waiting, does not affect VB6 form message loop.

Example:

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

When 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:

vb
Public Sub CallDevToolsProtocolMethod( _
    ByVal MethodName As String, _
    ByVal ParametersAsJson As String, _
    ByVal CustomEventId As String)

Parameters:

  • CustomEventId - Custom event ID for matching responses in the DevToolsProtocolResponse event

Example:

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

When 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

MethodParametersPurpose
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

MethodParametersPurpose
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

MethodParametersPurpose
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

MethodParametersPurpose
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

MethodParametersPurpose
Browser.getVersion{}Get browser version info

Simple Mode (cWebView2Cookies)

vb
' 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.GetCookiesFull
vb
' 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:

vb
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:

vb
' 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

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

Network Request Interception

vb
' Set extra request headers
wv.CallDevToolsProtocolMethodSync "Network.setExtraHTTPHeaders", _
    "{""headers"":{""X-Custom-Header"":""MyValue""}}"

Modifying DOM Attributes

vb
' 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

VB6 and LOGO copyright of Microsoft Corporation