cdp

package
v0.117.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 24 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Overview

This client is directly based on this doc.

You can treat it as a minimal example of how to use the DevTools Protocol, no complex abstraction.

It's thread-safe, and context first.

For basic usage, check this file.

For more info, check the unit tests.

Documentation

Overview

Package cdp for application layer communication with browser.

Example (Customize_cdp_log)
package main

import (
	"fmt"

	"github.com/projectdiscovery/rod/lib/cdp"
	"github.com/projectdiscovery/rod/lib/launcher"
	"github.com/projectdiscovery/rod/lib/utils"
)

func main() {
	ws := cdp.MustConnectWS(launcher.New().MustLaunch())

	cdp.New().
		Logger(utils.Log(func(args ...any) {
			switch v := args[0].(type) {
			case *cdp.Request:
				fmt.Printf("id: %d", v.ID)
			}
		})).
		Start(ws)
}

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultHandshakeTimeout = 30 * time.Second

DefaultHandshakeTimeout bounds the HTTP upgrade when the caller's context has no deadline.

View Source
var DefaultWriteTimeout = 60 * time.Second

DefaultWriteTimeout is used when WebSocket.WriteTimeout is zero.

View Source
var ErrConnClosed = errors.New("cdp: connection closed")

ErrConnClosed is matched by every error returned after the connection ends.

View Source
var ErrCtxDestroyed = &Error{
	Code:    -32000,
	Message: "Execution context was destroyed.",
}

ErrCtxDestroyed type.

View Source
var ErrCtxNotFound = &Error{
	Code:    -32000,
	Message: "Cannot find context with specified id",
}

ErrCtxNotFound type.

View Source
var ErrMessageTooLarge = errors.New("cdp: websocket message exceeds size limit")

ErrMessageTooLarge is returned when a frame exceeds MaxMessageSize.

View Source
var ErrNodeNotFoundAtPos = &Error{
	Code:    -32000,
	Message: "No node found at given location",
}

ErrNodeNotFoundAtPos type.

View Source
var ErrNotAttachedToActivePage = &Error{
	Code:    -32000,
	Message: "Not attached to an active page",
}

ErrNotAttachedToActivePage type.

View Source
var ErrObjNotFound = &Error{
	Code:    -32000,
	Message: "Could not find object with given id",
}

ErrObjNotFound type.

View Source
var ErrPipeClosed = errors.New("cdp: pipe closed")

ErrPipeClosed is returned when a pipe transport is used after Close.

View Source
var ErrSearchSessionNotFound = &Error{
	Code:    -32000,
	Message: "No search session with given id found",
}

ErrSearchSessionNotFound type.

View Source
var ErrSessionNotFound = &Error{
	Code:    -32001,
	Message: "Session with given id not found.",
}

ErrSessionNotFound type.

View Source
var MaxMessageSize = 64 << 20

MaxMessageSize is the largest CDP payload accepted from the peer. It is counted across continuation frames. Override on a WebSocket before Connect when a caller needs a different bound.

Functions

This section is empty.

Types

type BadHandshakeError

type BadHandshakeError struct {
	Status string
	Body   string
}

BadHandshakeError type.

func (*BadHandshakeError) Error

func (e *BadHandshakeError) Error() string

type Client

type Client struct {

	// OnDecodeError is called when a frame is not valid JSON.
	// The connection stays up. Nil logs and continues.
	OnDecodeError func(error)
	// contains filtered or unexported fields
}

Client is a devtools protocol connection instance.

Example
package main

import (
	"context"
	"fmt"

	"github.com/projectdiscovery/rod/lib/cdp"
	"github.com/projectdiscovery/rod/lib/launcher"
	"github.com/projectdiscovery/rod/lib/proto"
	"github.com/projectdiscovery/rod/lib/utils"
	"github.com/ysmood/gson"
)

func main() {
	ctx := context.Background()

	// launch a browser
	url := launcher.New().MustLaunch()

	// create a controller
	client := cdp.New().Start(cdp.MustConnectWS(url))

	go func() {
		for range client.Event() {
			// you must consume the events
			utils.Noop()
		}
	}()

	// Such as call this endpoint on the api doc:
	// https://chromedevtools.github.io/devtools-protocol/tot/Page#method-navigate
	// This will create a new tab and navigate to the test.com
	res, err := client.Call(ctx, "", "Target.createTarget", map[string]string{
		"url": "http://test.com",
	})
	utils.E(err)

	fmt.Println(len(gson.New(res).Get("targetId").Str()))

	// close browser by using the proto lib to encode json
	_ = proto.BrowserClose{}.Call(client)

}
Output:
32

func MustStartWithURL

func MustStartWithURL(ctx context.Context, u string, h http.Header) *Client

MustStartWithURL helper for ConnectURL.

func New

func New() *Client

New creates a cdp connection. Event is buffered so a slow consumer does not stall command responses until the buffer fills.

func StartWithURL

func StartWithURL(ctx context.Context, u string, h http.Header) (*Client, error)

StartWithURL helper to connect to the u with the default websocket lib.

func (*Client) Call

func (cdp *Client) Call(ctx context.Context, sessionID, method string, params any) ([]byte, error)

Call a method and wait for its response.

func (*Client) Close

func (cdp *Client) Close() error

Close the underlying transport. Pending and later calls fail with an error matching ErrConnClosed. Safe to call more than once.

func (*Client) Done

func (cdp *Client) Done() <-chan struct{}

Done is closed when the connection ends, by Close or by a transport error.

func (*Client) Err

func (cdp *Client) Err() error

Err returns why the connection ended, or nil while it is alive. The error matches ErrConnClosed and wraps the transport error.

func (*Client) Event

func (cdp *Client) Event() <-chan *Event

Event returns a channel of browser events. The channel is buffered. It is closed when the connection ends.

func (*Client) Logger

func (cdp *Client) Logger(l utils.Logger) *Client

Logger sets the logger.

func (*Client) Start

func (cdp *Client) Start(ws WebSocketable) *Client

Start to browser.

type ConnError

type ConnError struct {
	Err error
}

ConnError is returned for calls made after the transport failed. It matches ErrConnClosed and unwraps to the transport error.

func (*ConnError) Error

func (e *ConnError) Error() string

func (*ConnError) Unwrap

func (e *ConnError) Unwrap() []error

Unwrap returns ErrConnClosed and the transport error.

type Dialer

type Dialer interface {
	DialContext(ctx context.Context, network, address string) (net.Conn, error)
}

Dialer interface for WebSocket connection.

type Error

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

Error of the Response.

func (*Error) Error

func (e *Error) Error() string

Error stdlib interface.

func (Error) Is

func (e Error) Is(target error) bool

Is stdlib interface. ErrCtxDestroyed also matches the navigation message, so the retry logic keeps working on newer Chrome.

type Event

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

Event from browser.

func (Event) String

func (e Event) String() string

type Pipe

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

Pipe is a CDP transport over Chrome's --remote-debugging-pipe. Messages are NUL-delimited. Read and Send match WebSocketable so a Client can sit on top of it. The caller's Send buffer is not retained.

func NewPipe

func NewPipe(r, w *os.File) *Pipe

NewPipe wraps the read and write ends of a debugging pipe. Chrome writes to the parent's read end and reads from the parent's write end.

func (*Pipe) Close

func (p *Pipe) Close() error

Close closes both ends. Blocked Read and Send calls return ErrPipeClosed.

func (*Pipe) Read

func (p *Pipe) Read() ([]byte, error)

Read returns the next NUL-terminated message, without the NUL.

func (*Pipe) Send

func (p *Pipe) Send(msg []byte) error

Send writes one message and a trailing NUL.

type PipePair

type PipePair struct {
	ChromeRead  *os.File
	ChromeWrite *os.File
	ParentRead  *os.File
	ParentWrite *os.File
}

PipePair is the two ends passed to Chrome and the two ends kept by the parent.

func NewPipePair

func NewPipePair() (*PipePair, error)

NewPipePair creates an OS pipe pair for --remote-debugging-pipe. The child receives ChromeRead and ChromeWrite as extra files.

type Request

type Request struct {
	ID        int    `json:"id"`
	SessionID string `json:"sessionId,omitempty"`
	Method    string `json:"method"`
	Params    any    `json:"params,omitempty"`
}

Request to send to browser.

func (Request) String

func (req Request) String() string

type Response

type Response struct {
	ID     int             `json:"id"`
	Result json.RawMessage `json:"result,omitempty"`
	Error  *Error          `json:"error,omitempty"`
}

Response from browser.

func (Response) String

func (res Response) String() string

type WebSocket

type WebSocket struct {
	// Dialer is usually used for proxy.
	Dialer Dialer

	// MaxMessageSize caps a single message. Zero uses the package default.
	MaxMessageSize int

	// WriteTimeout fails and closes the connection when a frame cannot be
	// written in time. Zero uses DefaultWriteTimeout.
	WriteTimeout time.Duration

	// KeepAlive sends a ping at this interval and fails the connection when
	// nothing is read for three intervals. Zero disables it.
	KeepAlive time.Duration
	// contains filtered or unexported fields
}

WebSocket client for chromium. Both Read and Send are safe for concurrent use. Read returns only complete text messages. Control frames are handled inside the reader: ping is answered, close ends the stream.

func (*WebSocket) Close

func (ws *WebSocket) Close() error

Close the underlying connection. It is safe to call more than once.

func (*WebSocket) Connect

func (ws *WebSocket) Connect(ctx context.Context, wsURL string, header http.Header) error

Connect to browser.

func (*WebSocket) Read

func (ws *WebSocket) Read() ([]byte, error)

Read a text message from the browser.

func (*WebSocket) Send

func (ws *WebSocket) Send(msg []byte) error

Send a text message. The caller's buffer is not modified.

type WebSocketable

type WebSocketable interface {
	Send(data []byte) error
	Read() ([]byte, error)
}

WebSocketable enables you to choose the websocket lib you want to use.

func MustConnectWS

func MustConnectWS(wsURL string) WebSocketable

MustConnectWS helper to make a websocket connection.

Jump to

Keyboard shortcuts

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