cdp

package
v0.116.3 Latest Latest
Warning

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

Go to latest
Published: Jun 1, 2026 License: MIT Imports: 15 Imported by: ? modules, 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/GoCodeAlone/rod/lib/cdp"
	"github.com/GoCodeAlone/rod/lib/launcher"
	"github.com/GoCodeAlone/rod/lib/utils"
)

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

	cdp.New().
		Logger(utils.Log(func(args ...interface{}) {
			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 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 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 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.

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 {
	// contains filtered or unexported fields
}

Client is a devtools protocol connection instance.

Example
package main

import (
	"context"
	"fmt"

	"github.com/GoCodeAlone/rod/lib/cdp"
	"github.com/GoCodeAlone/rod/lib/launcher"
	"github.com/GoCodeAlone/rod/lib/proto"
	"github.com/GoCodeAlone/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, all messages from Client.Event must be received or they will block the client.

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 interface{}) ([]byte, error)

Call a method and wait for its response.

func (*Client) Event

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

Event returns a channel that will emit browser devtools protocol events. Must be consumed or will block producer.

func (*Client) Logger

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

Logger sets the logger to log all the requests, responses, and events transferred between Rod and the browser. The default format for each type is in file format.go.

func (*Client) Start

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

Start to browser.

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.

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 Request

type Request struct {
	ID        int         `json:"id"`
	SessionID string      `json:"sessionId,omitempty"`
	Method    string      `json:"method"`
	Params    interface{} `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
	// contains filtered or unexported fields
}

WebSocket client for chromium. It only implements a subset of WebSocket protocol. Both the Read and Write are thread-safe. Limitation: https://bugs.chromium.org/p/chromium/issues/detail?id=1069431 Ref: https://tools.ietf.org/html/rfc6455

func (*WebSocket) Close

func (ws *WebSocket) Close() error

Close the underlying connection.

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 message from browser.

func (*WebSocket) Send

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

Send a message to browser. Because we use zero-copy design, it will modify the content of the msg. It won't allocate new memory.

type WebSocketable

type WebSocketable interface {
	// Send text message only
	Send(data []byte) error
	// Read returns text message only
	Read() ([]byte, error)
}

WebSocketable enables you to choose the websocket lib you want to use. Such as you can easily wrap gorilla/websocket and use it as the transport layer.

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