cdp

package
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 29, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package cdp provides a Chrome DevTools Protocol client.

Index

Constants

View Source
const (
	CSSStartRuleUsageTracking = "CSS.startRuleUsageTracking"
	CSSStopRuleUsageTracking  = "CSS.stopRuleUsageTracking"
	CSSTakeCoverageDelta      = "CSS.takeCoverageDelta"
)

CSS coverage domain methods.

View Source
const (
	RuntimeConsoleAPICalled = "Runtime.consoleAPICalled"
	RuntimeExceptionThrown  = "Runtime.exceptionThrown"
	LogEntryAdded           = "Log.entryAdded"
)

Console debugger event names.

View Source
const (
	CPUNoThrottle = 1 // No throttling
	CPU2xSlowdown = 2 // 2x slowdown
	CPU4xSlowdown = 4 // 4x slowdown (mid-tier mobile)
	CPU6xSlowdown = 6 // 6x slowdown (low-end mobile)
)

CPU throttling rate presets.

View Source
const (
	ExtensionsLoadUnpacked = "Extensions.loadUnpacked"
	ExtensionsUninstall    = "Extensions.uninstall"
	ExtensionsGetAll       = "Extensions.getAll"
)

Extensions domain methods.

View Source
const (
	// HeapProfiler domain
	HeapProfilerEnable               = "HeapProfiler.enable"
	HeapProfilerDisable              = "HeapProfiler.disable"
	HeapProfilerTakeHeapSnapshot     = "HeapProfiler.takeHeapSnapshot"
	HeapProfilerAddHeapSnapshotChunk = "HeapProfiler.addHeapSnapshotChunk"

	// Network domain
	NetworkEnable            = "Network.enable"
	NetworkDisable           = "Network.disable"
	NetworkGetResponseBody   = "Network.getResponseBody"
	NetworkEmulateConditions = "Network.emulateNetworkConditions"

	// Emulation domain
	EmulationSetCPUThrottlingRate = "Emulation.setCPUThrottlingRate"

	// Profiler domain (for coverage)
	ProfilerEnable               = "Profiler.enable"
	ProfilerDisable              = "Profiler.disable"
	ProfilerStartPreciseCoverage = "Profiler.startPreciseCoverage"
	ProfilerStopPreciseCoverage  = "Profiler.stopPreciseCoverage"
	ProfilerTakePreciseCoverage  = "Profiler.takePreciseCoverage"

	// Debugger domain (for source maps)
	DebuggerEnable  = "Debugger.enable"
	DebuggerDisable = "Debugger.disable"

	// Runtime domain
	RuntimeEnable  = "Runtime.enable"
	RuntimeDisable = "Runtime.disable"

	// Log domain
	LogEnable  = "Log.enable"
	LogDisable = "Log.disable"
)

Common CDP domains and methods used by W3Pilot.

View Source
const (
	PageStartScreencast    = "Page.startScreencast"
	PageStopScreencast     = "Page.stopScreencast"
	PageScreencastFrameAck = "Page.screencastFrameAck"
	PageScreencastFrame    = "Page.screencastFrame"
)

Screencast domain methods.

Variables

View Source
var (
	NetworkOffline = NetworkConditions{
		Offline:            true,
		Latency:            0,
		DownloadThroughput: 0,
		UploadThroughput:   0,
	}

	NetworkSlow3G = NetworkConditions{
		Offline:            false,
		Latency:            400,
		DownloadThroughput: 400 * 1024 / 8,
		UploadThroughput:   400 * 1024 / 8,
		ConnectionType:     "cellular3g",
	}

	NetworkFast3G = NetworkConditions{
		Offline:            false,
		Latency:            150,
		DownloadThroughput: 1500 * 1024 / 8,
		UploadThroughput:   750 * 1024 / 8,
		ConnectionType:     "cellular3g",
	}

	Network4G = NetworkConditions{
		Offline:            false,
		Latency:            50,
		DownloadThroughput: 4000 * 1024 / 8,
		UploadThroughput:   3000 * 1024 / 8,
		ConnectionType:     "cellular4g",
	}

	NetworkWifi = NetworkConditions{
		Offline:            false,
		Latency:            10,
		DownloadThroughput: 30000 * 1024 / 8,
		UploadThroughput:   15000 * 1024 / 8,
		ConnectionType:     "wifi",
	}
)

Preset network conditions.

Functions

func DiscoverAny

func DiscoverAny() (port int, wsEndpoint string, err error)

DiscoverAny attempts to discover CDP using multiple methods. It tries running Chrome processes first, then falls back to common locations.

func DiscoverFromProcess

func DiscoverFromProcess(pid int) (port int, wsEndpoint string, err error)

DiscoverFromProcess attempts to find the DevToolsActivePort by examining the Chrome process command line for --user-data-dir.

func DiscoverFromRunningChrome

func DiscoverFromRunningChrome() (port int, wsEndpoint string, err error)

DiscoverFromRunningChrome finds the CDP port and page endpoint from a running Chrome process. This works by examining process command lines for --user-data-dir.

func DiscoverFromUserDataDir

func DiscoverFromUserDataDir(userDataDir string) (port int, wsEndpoint string, err error)

DiscoverFromUserDataDir reads the DevToolsActivePort file from Chrome's user data directory. Returns the CDP port and browser WebSocket endpoint.

Types

type BrowserInfo

type BrowserInfo struct {
	Port              int
	BrowserWSEndpoint string
	Browser           string
	ProtocolVersion   string
	UserAgent         string
	V8Version         string
	WebKitVersion     string
}

BrowserInfo contains information about a Chrome browser instance.

func GetBrowserInfo

func GetBrowserInfo(ctx context.Context, port int) (*BrowserInfo, error)

GetBrowserInfo fetches browser information from the CDP /json/version endpoint.

type CSSRuleUsage

type CSSRuleUsage struct {
	StyleSheetID string  `json:"styleSheetId"`
	StartOffset  float64 `json:"startOffset"`
	EndOffset    float64 `json:"endOffset"`
	Used         bool    `json:"used"`
}

CSSRuleUsage represents usage info for a CSS rule.

type CallFrame

type CallFrame struct {
	FunctionName string `json:"functionName"`
	ScriptID     string `json:"scriptId"`
	URL          string `json:"url"`
	LineNumber   int    `json:"lineNumber"`
	ColumnNumber int    `json:"columnNumber"`
}

CallFrame represents a single frame in a call stack.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is a Chrome DevTools Protocol client.

func NewClient

func NewClient() *Client

NewClient creates a new CDP client.

func (*Client) ClearCPUThrottling

func (c *Client) ClearCPUThrottling(ctx context.Context) error

ClearCPUThrottling clears CPU throttling (returns to normal).

func (*Client) ClearNetworkConditions

func (c *Client) ClearNetworkConditions(ctx context.Context) error

ClearNetworkConditions clears network emulation (returns to normal).

func (*Client) Close

func (c *Client) Close() error

Close closes the CDP connection.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, url string) error

Connect establishes a WebSocket connection to the CDP endpoint.

func (*Client) DisableNetwork

func (c *Client) DisableNetwork(ctx context.Context) error

DisableNetwork disables the Network domain.

func (*Client) EnableNetwork

func (c *Client) EnableNetwork(ctx context.Context) error

EnableNetwork enables the Network domain with response body capture.

func (*Client) GetAllExtensions

func (c *Client) GetAllExtensions(ctx context.Context) ([]ExtensionInfo, error)

GetAllExtensions returns all installed extensions.

func (*Client) GetResponseBody

func (c *Client) GetResponseBody(ctx context.Context, requestID string, saveTo string) (*ResponseBody, error)

GetResponseBody retrieves the body of a network response. If saveTo is provided, the body is saved to that path.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns true if the client is connected.

func (*Client) LoadUnpackedExtension

func (c *Client) LoadUnpackedExtension(ctx context.Context, path string) (string, error)

LoadUnpackedExtension loads an unpacked extension from a directory. Returns the extension ID if successful.

func (*Client) OnEvent

func (c *Client) OnEvent(method string, handler EventHandler)

OnEvent registers a handler for CDP events.

func (*Client) RemoveEventHandlers

func (c *Client) RemoveEventHandlers(method string)

RemoveEventHandlers removes all handlers for the given method.

func (*Client) Send

func (c *Client) Send(ctx context.Context, method string, params interface{}) (json.RawMessage, error)

Send sends a CDP command and waits for the response.

func (*Client) SetCPUThrottlingRate

func (c *Client) SetCPUThrottlingRate(ctx context.Context, rate int) error

SetCPUThrottlingRate sets CPU throttling. rate=1 means no throttling, rate=4 means 4x slowdown.

func (*Client) SetNetworkConditions

func (c *Client) SetNetworkConditions(ctx context.Context, conditions NetworkConditions) error

SetNetworkConditions sets network emulation conditions.

func (*Client) TakeHeapSnapshot

func (c *Client) TakeHeapSnapshot(ctx context.Context, path string) (*HeapSnapshot, error)

TakeHeapSnapshot captures a V8 heap snapshot and saves it to a file. If path is empty, a temporary file is created.

func (*Client) URL

func (c *Client) URL() string

URL returns the WebSocket URL this client is connected to.

func (*Client) UninstallExtension

func (c *Client) UninstallExtension(ctx context.Context, id string) error

UninstallExtension removes an extension by ID.

type ConsoleDebugger

type ConsoleDebugger struct {
	// contains filtered or unexported fields
}

ConsoleDebugger captures console messages with stack traces.

func NewConsoleDebugger

func NewConsoleDebugger(client *Client) *ConsoleDebugger

NewConsoleDebugger creates a new console debugger.

func (*ConsoleDebugger) Clear

func (d *ConsoleDebugger) Clear()

Clear clears all captured entries.

func (*ConsoleDebugger) Disable

func (d *ConsoleDebugger) Disable(ctx context.Context) error

Disable stops capturing console messages.

func (*ConsoleDebugger) Enable

func (d *ConsoleDebugger) Enable(ctx context.Context) error

Enable starts capturing console messages with stack traces.

func (*ConsoleDebugger) Entries

func (d *ConsoleDebugger) Entries() []ConsoleEntry

Entries returns all captured console entries.

func (*ConsoleDebugger) Errors

func (d *ConsoleDebugger) Errors() []ExceptionDetails

Errors returns all captured exceptions.

func (*ConsoleDebugger) IsEnabled

func (d *ConsoleDebugger) IsEnabled() bool

IsEnabled returns whether the debugger is enabled.

func (*ConsoleDebugger) Logs

func (d *ConsoleDebugger) Logs() []LogEntry

Logs returns all captured browser log entries.

func (*ConsoleDebugger) OnConsole

func (d *ConsoleDebugger) OnConsole(handler func(*ConsoleEntry))

OnConsole registers a handler for console messages.

func (*ConsoleDebugger) OnException

func (d *ConsoleDebugger) OnException(handler func(*ExceptionDetails))

OnException registers a handler for exceptions.

func (*ConsoleDebugger) OnLog

func (d *ConsoleDebugger) OnLog(handler func(*LogEntry))

OnLog registers a handler for browser log entries.

type ConsoleEntry

type ConsoleEntry struct {
	Type       ConsoleMessageType `json:"type"`
	Args       []RemoteObject     `json:"args"`
	StackTrace *StackTrace        `json:"stackTrace,omitempty"`
	Timestamp  float64            `json:"timestamp"`
	// Formatted message extracted from args
	Text string `json:"text"`
}

ConsoleEntry represents a console API call with full stack trace.

type ConsoleMessageType

type ConsoleMessageType string

ConsoleMessageType represents the type of console message.

const (
	ConsoleLog     ConsoleMessageType = "log"
	ConsoleDebug   ConsoleMessageType = "debug"
	ConsoleInfo    ConsoleMessageType = "info"
	ConsoleError   ConsoleMessageType = "error"
	ConsoleWarning ConsoleMessageType = "warning"
	ConsoleDir     ConsoleMessageType = "dir"
	ConsoleDirXML  ConsoleMessageType = "dirxml"
	ConsoleTable   ConsoleMessageType = "table"
	ConsoleTrace   ConsoleMessageType = "trace"
	ConsoleClear   ConsoleMessageType = "clear"
	ConsoleAssert  ConsoleMessageType = "assert"
)

type Coverage

type Coverage struct {
	// contains filtered or unexported fields
}

Coverage manages code coverage collection.

func NewCoverage

func NewCoverage(client *Client) *Coverage

NewCoverage creates a new coverage manager.

func (*Coverage) IsRunning

func (c *Coverage) IsRunning() bool

IsRunning returns whether coverage collection is active.

func (*Coverage) Start

func (c *Coverage) Start(ctx context.Context) error

Start enables both JS and CSS coverage collection.

func (*Coverage) StartCSS

func (c *Coverage) StartCSS(ctx context.Context) error

StartCSS enables CSS coverage collection.

func (*Coverage) StartJS

func (c *Coverage) StartJS(ctx context.Context, callCount, detailed bool) error

StartJS enables JavaScript coverage collection. callCount: collect execution counts per block detailed: collect block-level coverage (vs function-level)

func (*Coverage) Stop

func (c *Coverage) Stop(ctx context.Context) (*CoverageReport, error)

Stop stops all coverage collection and returns the results.

func (*Coverage) StopCSS

func (c *Coverage) StopCSS(ctx context.Context) ([]CSSRuleUsage, error)

StopCSS stops CSS coverage and returns the results.

func (*Coverage) StopJS

func (c *Coverage) StopJS(ctx context.Context) ([]ScriptCoverage, error)

StopJS stops JavaScript coverage and returns the results.

type CoverageRange

type CoverageRange struct {
	StartOffset int `json:"startOffset"`
	EndOffset   int `json:"endOffset"`
	Count       int `json:"count"`
}

CoverageRange represents a range of code that was covered.

type CoverageReport

type CoverageReport struct {
	JS  []ScriptCoverage `json:"js"`
	CSS []CSSRuleUsage   `json:"css"`
}

CoverageReport contains JS and CSS coverage data.

func (*CoverageReport) Summary

func (r *CoverageReport) Summary() CoverageSummary

Summary returns a high-level summary of coverage data.

type CoverageSummary

type CoverageSummary struct {
	JSScripts       int     `json:"jsScripts"`
	JSFunctions     int     `json:"jsFunctions"`
	JSCoveredRanges int     `json:"jsCoveredRanges"`
	CSSRules        int     `json:"cssRules"`
	CSSUsedRules    int     `json:"cssUsedRules"`
	CSSUnusedRules  int     `json:"cssUnusedRules"`
	CSSUsagePercent float64 `json:"cssUsagePercent"`
}

CoverageSummary provides a high-level summary of coverage.

type Error

type Error struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    string `json:"data,omitempty"`
}

Error represents a CDP error response.

func (*Error) Error

func (e *Error) Error() string

type Event

type Event struct {
	Method string          `json:"method"`
	Params json.RawMessage `json:"params"`
}

Event represents a CDP event.

type EventHandler

type EventHandler func(params json.RawMessage)

EventHandler is a callback for CDP events.

type ExceptionDetails

type ExceptionDetails struct {
	ExceptionID        int           `json:"exceptionId"`
	Text               string        `json:"text"`
	LineNumber         int           `json:"lineNumber"`
	ColumnNumber       int           `json:"columnNumber"`
	ScriptID           string        `json:"scriptId,omitempty"`
	URL                string        `json:"url,omitempty"`
	StackTrace         *StackTrace   `json:"stackTrace,omitempty"`
	Exception          *RemoteObject `json:"exception,omitempty"`
	ExecutionContextID int           `json:"executionContextId,omitempty"`
}

ExceptionDetails contains information about an exception.

type ExtensionInfo

type ExtensionInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Version     string `json:"version,omitempty"`
	Description string `json:"description,omitempty"`
	Enabled     bool   `json:"enabled"`
	Path        string `json:"path,omitempty"`
}

ExtensionInfo contains information about a browser extension.

type FunctionCoverage

type FunctionCoverage struct {
	FunctionName    string          `json:"functionName"`
	Ranges          []CoverageRange `json:"ranges"`
	IsBlockCoverage bool            `json:"isBlockCoverage"`
}

FunctionCoverage represents coverage for a function.

type GetResponseBodyResult

type GetResponseBodyResult struct {
	Body          string `json:"body"`
	Base64Encoded bool   `json:"base64Encoded"`
}

GetResponseBodyResult is the result of Network.getResponseBody.

type HeapSnapshot

type HeapSnapshot struct {
	Path string // File path where snapshot is saved
	Size int64  // Size in bytes
}

HeapSnapshot represents a captured heap snapshot.

type HeapSnapshotChunk

type HeapSnapshotChunk struct {
	Chunk string `json:"chunk"`
}

HeapSnapshotChunk is sent during heap snapshot capture.

type LogEntry

type LogEntry struct {
	Source     string      `json:"source"` // network, violation, intervention, etc.
	Level      string      `json:"level"`  // verbose, info, warning, error
	Text       string      `json:"text"`
	Timestamp  float64     `json:"timestamp"`
	URL        string      `json:"url,omitempty"`
	LineNumber int         `json:"lineNumber,omitempty"`
	StackTrace *StackTrace `json:"stackTrace,omitempty"`
}

LogEntry represents a browser log entry (deprecations, interventions, etc).

type Message

type Message struct {
	ID     int64           `json:"id,omitempty"`
	Method string          `json:"method,omitempty"`
	Params json.RawMessage `json:"params,omitempty"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  *Error          `json:"error,omitempty"`
}

Message represents a CDP message (request or response).

type NetworkConditions

type NetworkConditions struct {
	Offline            bool    `json:"offline"`
	Latency            float64 `json:"latency"`            // ms
	DownloadThroughput float64 `json:"downloadThroughput"` // bytes/sec
	UploadThroughput   float64 `json:"uploadThroughput"`   // bytes/sec
	ConnectionType     string  `json:"connectionType,omitempty"`
}

NetworkConditions represents network throttling settings.

type RemoteObject

type RemoteObject struct {
	Type        string `json:"type"`
	Subtype     string `json:"subtype,omitempty"`
	ClassName   string `json:"className,omitempty"`
	Value       any    `json:"value,omitempty"`
	Description string `json:"description,omitempty"`
	ObjectID    string `json:"objectId,omitempty"`
}

RemoteObject represents a JavaScript object.

type ResponseBody

type ResponseBody struct {
	Body          string // Raw body (or base64 encoded for binary)
	Base64Encoded bool   // True if body is base64 encoded
	Size          int    // Size in bytes
	Path          string // File path if saved to disk
}

ResponseBody represents the body of a network response.

type Screencast

type Screencast struct {
	// contains filtered or unexported fields
}

Screencast manages screencast capture.

func NewScreencast

func NewScreencast(client *Client) *Screencast

NewScreencast creates a new screencast manager.

func (*Screencast) IsRunning

func (s *Screencast) IsRunning() bool

IsRunning returns whether screencast is active.

func (*Screencast) Start

Start begins screencast capture.

func (*Screencast) Stop

func (s *Screencast) Stop(ctx context.Context) error

Stop ends screencast capture.

type ScreencastFormat

type ScreencastFormat string

ScreencastFormat represents the image format for screencast.

const (
	ScreencastFormatJPEG ScreencastFormat = "jpeg"
	ScreencastFormatPNG  ScreencastFormat = "png"
)

type ScreencastFrame

type ScreencastFrame struct {
	Data      string             `json:"data"` // Base64-encoded image data
	Metadata  ScreencastMetadata `json:"metadata"`
	SessionID int                `json:"sessionId"`
}

ScreencastFrame represents a captured frame.

type ScreencastFrameHandler

type ScreencastFrameHandler func(frame *ScreencastFrame)

ScreencastFrameHandler is called for each captured frame.

type ScreencastMetadata

type ScreencastMetadata struct {
	OffsetTop       float64 `json:"offsetTop"`
	PageScaleFactor float64 `json:"pageScaleFactor"`
	DeviceWidth     int     `json:"deviceWidth"`
	DeviceHeight    int     `json:"deviceHeight"`
	ScrollOffsetX   float64 `json:"scrollOffsetX"`
	ScrollOffsetY   float64 `json:"scrollOffsetY"`
	Timestamp       float64 `json:"timestamp,omitempty"`
}

ScreencastMetadata contains frame metadata.

type ScreencastOptions

type ScreencastOptions struct {
	Format        ScreencastFormat `json:"format,omitempty"`        // Image format (jpeg or png)
	Quality       int              `json:"quality,omitempty"`       // Image quality (0-100, jpeg only)
	MaxWidth      int              `json:"maxWidth,omitempty"`      // Maximum width
	MaxHeight     int              `json:"maxHeight,omitempty"`     // Maximum height
	EveryNthFrame int              `json:"everyNthFrame,omitempty"` // Skip frames (1 = every frame)
}

ScreencastOptions configures screencast capture.

type ScriptCoverage

type ScriptCoverage struct {
	ScriptID  string             `json:"scriptId"`
	URL       string             `json:"url"`
	Functions []FunctionCoverage `json:"functions"`
}

ScriptCoverage represents coverage for a script.

type StackTrace

type StackTrace struct {
	Description string      `json:"description,omitempty"`
	CallFrames  []CallFrame `json:"callFrames"`
	Parent      *StackTrace `json:"parent,omitempty"`
}

StackTrace represents a JavaScript stack trace.

type Target

type Target struct {
	ID                   string `json:"id"`
	Type                 string `json:"type"`
	Title                string `json:"title"`
	URL                  string `json:"url"`
	WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
	DevtoolsFrontendURL  string `json:"devtoolsFrontendUrl"`
}

Target represents a CDP target (page, worker, etc.).

func FindPageTarget

func FindPageTarget(ctx context.Context, port int, url string) (*Target, error)

FindPageTarget finds the first page target matching the given URL. If url is empty, returns the first page target.

func ListTargets

func ListTargets(ctx context.Context, port int) ([]Target, error)

ListTargets fetches the list of available CDP targets.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL