Documentation
¶
Overview ¶
Package cdp provides a Chrome DevTools Protocol client.
Index ¶
- Constants
- Variables
- func DiscoverAny() (port int, wsEndpoint string, err error)
- func DiscoverFromProcess(pid int) (port int, wsEndpoint string, err error)
- func DiscoverFromRunningChrome() (port int, wsEndpoint string, err error)
- func DiscoverFromUserDataDir(userDataDir string) (port int, wsEndpoint string, err error)
- type BrowserInfo
- type CSSRuleUsage
- type CallFrame
- type Client
- func (c *Client) ClearCPUThrottling(ctx context.Context) error
- func (c *Client) ClearNetworkConditions(ctx context.Context) error
- func (c *Client) Close() error
- func (c *Client) Connect(ctx context.Context, url string) error
- func (c *Client) DisableNetwork(ctx context.Context) error
- func (c *Client) EnableNetwork(ctx context.Context) error
- func (c *Client) GetAllExtensions(ctx context.Context) ([]ExtensionInfo, error)
- func (c *Client) GetResponseBody(ctx context.Context, requestID string, saveTo string) (*ResponseBody, error)
- func (c *Client) IsConnected() bool
- func (c *Client) LoadUnpackedExtension(ctx context.Context, path string) (string, error)
- func (c *Client) OnEvent(method string, handler EventHandler)
- func (c *Client) RemoveEventHandlers(method string)
- func (c *Client) Send(ctx context.Context, method string, params interface{}) (json.RawMessage, error)
- func (c *Client) SetCPUThrottlingRate(ctx context.Context, rate int) error
- func (c *Client) SetNetworkConditions(ctx context.Context, conditions NetworkConditions) error
- func (c *Client) TakeHeapSnapshot(ctx context.Context, path string) (*HeapSnapshot, error)
- func (c *Client) URL() string
- func (c *Client) UninstallExtension(ctx context.Context, id string) error
- type ConsoleDebugger
- func (d *ConsoleDebugger) Clear()
- func (d *ConsoleDebugger) Disable(ctx context.Context) error
- func (d *ConsoleDebugger) Enable(ctx context.Context) error
- func (d *ConsoleDebugger) Entries() []ConsoleEntry
- func (d *ConsoleDebugger) Errors() []ExceptionDetails
- func (d *ConsoleDebugger) IsEnabled() bool
- func (d *ConsoleDebugger) Logs() []LogEntry
- func (d *ConsoleDebugger) OnConsole(handler func(*ConsoleEntry))
- func (d *ConsoleDebugger) OnException(handler func(*ExceptionDetails))
- func (d *ConsoleDebugger) OnLog(handler func(*LogEntry))
- type ConsoleEntry
- type ConsoleMessageType
- type Coverage
- func (c *Coverage) IsRunning() bool
- func (c *Coverage) Start(ctx context.Context) error
- func (c *Coverage) StartCSS(ctx context.Context) error
- func (c *Coverage) StartJS(ctx context.Context, callCount, detailed bool) error
- func (c *Coverage) Stop(ctx context.Context) (*CoverageReport, error)
- func (c *Coverage) StopCSS(ctx context.Context) ([]CSSRuleUsage, error)
- func (c *Coverage) StopJS(ctx context.Context) ([]ScriptCoverage, error)
- type CoverageRange
- type CoverageReport
- type CoverageSummary
- type Error
- type Event
- type EventHandler
- type ExceptionDetails
- type ExtensionInfo
- type FunctionCoverage
- type GetResponseBodyResult
- type HeapSnapshot
- type HeapSnapshotChunk
- type LogEntry
- type Message
- type NetworkConditions
- type RemoteObject
- type ResponseBody
- type Screencast
- type ScreencastFormat
- type ScreencastFrame
- type ScreencastFrameHandler
- type ScreencastMetadata
- type ScreencastOptions
- type ScriptCoverage
- type StackTrace
- type Target
Constants ¶
const ( CSSStartRuleUsageTracking = "CSS.startRuleUsageTracking" CSSStopRuleUsageTracking = "CSS.stopRuleUsageTracking" CSSTakeCoverageDelta = "CSS.takeCoverageDelta" )
CSS coverage domain methods.
const ( RuntimeConsoleAPICalled = "Runtime.consoleAPICalled" RuntimeExceptionThrown = "Runtime.exceptionThrown" LogEntryAdded = "Log.entryAdded" )
Console debugger event names.
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.
const ( ExtensionsLoadUnpacked = "Extensions.loadUnpacked" ExtensionsUninstall = "Extensions.uninstall" ExtensionsGetAll = "Extensions.getAll" )
Extensions domain methods.
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.
const ( PageStartScreencast = "Page.startScreencast" PageStopScreencast = "Page.stopScreencast" PageScreencastFrameAck = "Page.screencastFrameAck" PageScreencastFrame = "Page.screencastFrame" )
Screencast domain methods.
Variables ¶
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 ¶
DiscoverAny attempts to discover CDP using multiple methods. It tries running Chrome processes first, then falls back to common locations.
func DiscoverFromProcess ¶
DiscoverFromProcess attempts to find the DevToolsActivePort by examining the Chrome process command line for --user-data-dir.
func DiscoverFromRunningChrome ¶
DiscoverFromRunningChrome finds the CDP port and page endpoint from a running Chrome process. This works by examining process command lines for --user-data-dir.
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 (*Client) ClearCPUThrottling ¶
ClearCPUThrottling clears CPU throttling (returns to normal).
func (*Client) ClearNetworkConditions ¶
ClearNetworkConditions clears network emulation (returns to normal).
func (*Client) DisableNetwork ¶
DisableNetwork disables the Network domain.
func (*Client) EnableNetwork ¶
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 ¶
IsConnected returns true if the client is connected.
func (*Client) LoadUnpackedExtension ¶
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 ¶
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 ¶
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 ¶
TakeHeapSnapshot captures a V8 heap snapshot and saves it to a file. If path is empty, a temporary file is created.
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 ¶
NewCoverage creates a new coverage manager.
func (*Coverage) StartJS ¶
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.
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.
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 ¶
func (s *Screencast) Start(ctx context.Context, opts *ScreencastOptions, handler ScreencastFrameHandler) error
Start begins 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 ¶
FindPageTarget finds the first page target matching the given URL. If url is empty, returns the first page target.