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)
}
Output:
Index ¶
- Variables
- type BadHandshakeError
- type Client
- func (cdp *Client) Call(ctx context.Context, sessionID, method string, params any) ([]byte, error)
- func (cdp *Client) Close() error
- func (cdp *Client) Done() <-chan struct{}
- func (cdp *Client) Err() error
- func (cdp *Client) Event() <-chan *Event
- func (cdp *Client) Logger(l utils.Logger) *Client
- func (cdp *Client) Start(ws WebSocketable) *Client
- type ConnError
- type Dialer
- type Error
- type Event
- type Pipe
- type PipePair
- type Request
- type Response
- type WebSocket
- type WebSocketable
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultHandshakeTimeout = 30 * time.Second
DefaultHandshakeTimeout bounds the HTTP upgrade when the caller's context has no deadline.
var DefaultWriteTimeout = 60 * time.Second
DefaultWriteTimeout is used when WebSocket.WriteTimeout is zero.
var ErrConnClosed = errors.New("cdp: connection closed")
ErrConnClosed is matched by every error returned after the connection ends.
var ErrCtxDestroyed = &Error{
Code: -32000,
Message: "Execution context was destroyed.",
}
ErrCtxDestroyed type.
var ErrCtxNotFound = &Error{
Code: -32000,
Message: "Cannot find context with specified id",
}
ErrCtxNotFound type.
var ErrMessageTooLarge = errors.New("cdp: websocket message exceeds size limit")
ErrMessageTooLarge is returned when a frame exceeds MaxMessageSize.
var ErrNodeNotFoundAtPos = &Error{
Code: -32000,
Message: "No node found at given location",
}
ErrNodeNotFoundAtPos type.
var ErrNotAttachedToActivePage = &Error{
Code: -32000,
Message: "Not attached to an active page",
}
ErrNotAttachedToActivePage type.
var ErrObjNotFound = &Error{
Code: -32000,
Message: "Could not find object with given id",
}
ErrObjNotFound type.
var ErrPipeClosed = errors.New("cdp: pipe closed")
ErrPipeClosed is returned when a pipe transport is used after Close.
var ErrSearchSessionNotFound = &Error{
Code: -32000,
Message: "No search session with given id found",
}
ErrSearchSessionNotFound type.
var ErrSessionNotFound = &Error{
Code: -32001,
Message: "Session with given id not found.",
}
ErrSessionNotFound type.
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 ¶
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 ¶
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 ¶
StartWithURL helper to connect to the u with the default websocket lib.
func (*Client) Close ¶
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 ¶
Err returns why the connection ended, or nil while it is alive. The error matches ErrConnClosed and wraps the transport error.
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.
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.
type Event ¶
type Event struct {
SessionID string `json:"sessionId,omitempty"`
Method string `json:"method"`
Params json.RawMessage `json:"params,omitempty"`
}
Event from browser.
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 ¶
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.
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 ¶
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.
type Response ¶
type Response struct {
ID int `json:"id"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
}
Response from browser.
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.
type WebSocketable ¶
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.