godet

package module
v0.0.0-...-d17141a Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 13 Imported by: 88

README

Go Documentation Go Report Card Actions Status

godet

Remote client for Chrome DevTools

Installation

$ go get github.com/raff/godet

Documentation

http://godoc.org/github.com/raff/godet

Example

A pretty complete example is available at cmd/godet/main.go. This example is available at examples/example.go.

import "github.com/raff/godet"

// connect to Chrome instance
remote, err := godet.Connect("localhost:9222", true)
if err != nil {
    fmt.Println("cannot connect to Chrome instance:", err)
    return
}

// disconnect when done
defer remote.Close()

// get browser and protocol version
version, _ := remote.Version()
fmt.Println(version)

// get list of open tabs
tabs, _ := remote.TabList("")
fmt.Println(tabs)

// install some callbacks
remote.CallbackEvent(godet.EventClosed, func(params godet.Params) {
    fmt.Println("RemoteDebugger connection terminated.")
})

remote.CallbackEvent("Network.requestWillBeSent", func(params godet.Params) {
    fmt.Println("requestWillBeSent",
        params["type"],
        params["documentURL"],
        params["request"].(map[string]interface{})["url"])
})

remote.CallbackEvent("Network.responseReceived", func(params godet.Params) {
    fmt.Println("responseReceived",
        params["type"],
        params["response"].(map[string]interface{})["url"])
})

remote.CallbackEvent("Log.entryAdded", func(params godet.Params) {
    entry := params["entry"].(map[string]interface{})
    fmt.Println("LOG", entry["type"], entry["level"], entry["text"])
})

// block loading of most images
_ = remote.SetBlockedURLs("*.jpg", "*.png", "*.gif")

// create new tab
tab, _ := remote.NewTab("https://www.google.com")
fmt.Println(tab)

// enable event processing
remote.RuntimeEvents(true)
remote.NetworkEvents(true)
remote.PageEvents(true)
remote.DOMEvents(true)
remote.LogEvents(true)

// navigate in existing tab
_ = remote.ActivateTab(tabs[0])

// re-enable events when changing active tab
remote.AllEvents(true) // enable all events

_, _ = remote.Navigate("https://www.google.com")

// evaluate Javascript expression in existing context
res, _ := remote.EvaluateWrap(`
    console.log("hello from godet!")
    return 42;
`)
fmt.Println(res)

// take a screenshot
_ = remote.SaveScreenshot("screenshot.png", 0644, 0, true)

// or save page as PDF
_ = remote.SavePDF("page.pdf", 0644)

Documentation

Overview

Package godet implements a client to interact with an instance of Chrome via the Remote Debugging Protocol.

The package provides a high-level interface to Chrome DevTools Protocol, allowing you to: - Control Chrome/Chromium browser programmatically - Automate web page interactions - Capture screenshots and PDF files - Monitor network traffic - Debug JavaScript - Profile page performance - And more...

Basic usage:

debugger, err := godet.Connect("localhost:9222", true)
if err != nil {
    log.Fatal(err)
}
defer debugger.Close()

// Navigate to a page
debugger.Navigate("https://example.com")

// Take a screenshot
debugger.SaveScreenshot("screenshot.png", 0644, 100, false)

For more examples and detailed documentation, see: https://developer.chrome.com/devtools/docs/debugger-protocol

Index

Constants

View Source
const (
	// EventClosed represents the "RemoteDebugger.closed" event.
	// It is emitted when RemoteDebugger.Close() is called.
	EventClosed = "RemoteDebugger.closed"
	// EventClosed represents the "RemoteDebugger.disconnected" event.
	// It is emitted when we lose connection with the debugger and we stop reading events
	EventDisconnect = "RemoteDebugger.disconnected"

	// NavigationProceed allows the navigation
	NavigationProceed = NavigationResponse("Proceed")
	// NavigationCancel cancels the navigation
	NavigationCancel = NavigationResponse("Cancel")
	// NavigationCancelAndIgnore cancels the navigation and makes the requester of the navigation acts like the request was never made.
	NavigationCancelAndIgnore = NavigationResponse("CancelAndIgnore")

	ErrorReasonFailed               = ErrorReason("Failed")
	ErrorReasonAborted              = ErrorReason("Aborted")
	ErrorReasonTimedOut             = ErrorReason("TimedOut")
	ErrorReasonAccessDenied         = ErrorReason("AccessDenied")
	ErrorReasonConnectionClosed     = ErrorReason("ConnectionClosed")
	ErrorReasonConnectionReset      = ErrorReason("ConnectionReset")
	ErrorReasonConnectionRefused    = ErrorReason("ConnectionRefused")
	ErrorReasonConnectionAborted    = ErrorReason("ConnectionAborted")
	ErrorReasonConnectionFailed     = ErrorReason("ConnectionFailed")
	ErrorReasonNameNotResolved      = ErrorReason("NameNotResolved")
	ErrorReasonInternetDisconnected = ErrorReason("InternetDisconnected")
	ErrorReasonAddressUnreachable   = ErrorReason("AddressUnreachable")
	ErrorReasonBlockedByClient      = ErrorReason("BlockedByClient")
	ErrorReasonBlockedByResponse    = ErrorReason("BlockedByResponse")

	// VirtualTimePolicyAdvance specifies that if the scheduler runs out of immediate work, the virtual time base may fast forward to allow the next delayed task (if any) to run
	VirtualTimePolicyAdvance = VirtualTimePolicy("advance")
	// VirtualTimePolicyPause specifies that the virtual time base may not advance
	VirtualTimePolicyPause = VirtualTimePolicy("pause")
	// VirtualTimePolicyPauseIfNetworkFetchesPending specifies that the virtual time base may not advance if there are any pending resource fetches.
	VirtualTimePolicyPauseIfNetworkFetchesPending = VirtualTimePolicy("pauseIfNetworkFetchesPending")

	AllowDownload   = DownloadBehavior("allow")
	NameDownload    = DownloadBehavior("allowAndName")
	DenyDownload    = DownloadBehavior("deny")
	DefaultDownload = DownloadBehavior("default")
)
View Source
const (
	NoTransition = TransitionType("")
	Reload       = TransitionType("reload")
)
View Source
const (
	ResourceTypeDocument           = ResourceType("Document")
	ResourceTypeStylesheet         = ResourceType("Stylesheet")
	ResourceTypeImage              = ResourceType("Image")
	ResourceTypeMedia              = ResourceType("Media")
	ResourceTypeFont               = ResourceType("Font")
	ResourceTypeScript             = ResourceType("Script")
	ResourceTypeTextTrack          = ResourceType("TextTrack")
	ResourceTypeXHR                = ResourceType("XHR")
	ResourceTypeFetch              = ResourceType("Fetch")
	ResourceTypeEventSource        = ResourceType("EventSource")
	ResourceTypeWebSocket          = ResourceType("WebSocket")
	ResourceTypeManifest           = ResourceType("Manifest")
	ResourceTypeSignedExchange     = ResourceType("SignedExchange")
	ResourceTypePing               = ResourceType("Ping")
	ResourceTypeCSPViolationReport = ResourceType("CSPViolationReport")
	ResourceTypeOther              = ResourceType("Other")
)
View Source
const (
	StageRequest         = InterceptionStage("Request")
	StageHeadersReceived = InterceptionStage("HeadersReceived")

	RequestStageRequest  = RequestStage("Request")
	RequestStageResponse = RequestStage("Response")
)
View Source
const (
	MouseMove    MouseEvent = "mouseMoved"
	MousePress   MouseEvent = "mousePressed"
	MouseRelease MouseEvent = "mouseReleased"

	NoModifier KeyModifier = 0
	AltKey     KeyModifier = 1
	CtrlKey    KeyModifier = 2
	MetaKey    KeyModifier = 4
	CommandKey KeyModifier = 4
	ShiftKey   KeyModifier = 8
)

Variables

View Source
var (
	// ErrorNoActiveTab is returned if there are no active tabs (of type "page")
	ErrorNoActiveTab = errors.New("no active tab")
	// ErrorNoWsURL is returned if the active tab has no websocket URL
	ErrorNoWsURL = errors.New("no websocket URL")
	// ErrorNoResponse is returned if a method was expecting a response but got nil instead
	ErrorNoResponse = errors.New("no response")
	// ErrorClose is returned if a method is called after the connection has been close
	ErrorClose = errors.New("closed")

	MaxReadBufferSize  = 0          // default gorilla/websocket buffer size
	MaxWriteBufferSize = 100 * 1024 // this should be large enough to send large scripts
)

Functions

func Budget

func Budget(budget int) setVirtualTimerPolicyOption

If set, after this many virtual milliseconds have elapsed virtual time will be paused and a\nvirtualTimeBudgetExpired event is sent.

func InitialVirtualTime

func InitialVirtualTime(t time.Time) setVirtualTimerPolicyOption

If set, base::Time::Now will be overriden to initially return this value.

func MaxVirtualTimeTaskStarvationCount

func MaxVirtualTimeTaskStarvationCount(max int) setVirtualTimerPolicyOption

If set this specifies the maximum number of tasks that can be run before virtual is forced\nforwards to prevent deadlock.

func WaitForNavigation

func WaitForNavigation(wait bool) setVirtualTimerPolicyOption

If set the virtual time policy change should be deferred until any frame starts navigating.\nNote any previous deferred policy change is superseded.

Types

type ConnectOption

type ConnectOption func(c *httpclient.HttpClient)

ConnectOption represents a function that modifies the HTTP client configuration. These options can be passed to the Connect function to customize the connection.

func Headers

func Headers(headers map[string]string) ConnectOption

Headers set specified HTTP headers

func Host

func Host(host string) ConnectOption

Host set the host header

type Cookie struct {
	Name     string  `json:"name"`     // Cookie name
	Value    string  `json:"value"`    // Cookie value
	Domain   string  `json:"domain"`   // Cookie domain
	Path     string  `json:"path"`     // Cookie path
	Size     int     `json:"size"`     // Size in bytes
	Expires  float64 `json:"expires"`  // Unix time in seconds
	HttpOnly bool    `json:"httpOnly"` // HttpOnly flag
	Secure   bool    `json:"secure"`   // Secure flag
	Session  bool    `json:"session"`  // Session cookie flag
	SameSite string  `json:"sameSite"` // SameSite policy
}

Cookie represents a browser cookie with all its attributes. This structure matches the Cookie object in the Chrome DevTools Protocol.

type Domain

type Domain struct {
	Name    string `json:"name"`    // Domain name
	Version string `json:"version"` // Domain version
}

Domain holds a domain name and version. A domain represents a group of related DevTools commands and events.

type DownloadBehavior

type DownloadBehavior string

DownloadBehaviour defines the type for Page.SetDownloadBehavior

type ErrorReason

type ErrorReason string

ErrorReason defines what error should be generated to abort a request in ContinueInterceptedRequest

type EvaluateError

type EvaluateError struct {
	ErrorDetails     map[string]interface{} // Error details
	ExceptionDetails map[string]interface{} // Exception details
}

EvaluateError is returned by Evaluate in case of JavaScript expression errors. It provides detailed information about the error, including line and column numbers.

func (EvaluateError) Error

func (err EvaluateError) Error() string

Error implements the error interface for EvaluateError.

type EvaluateOption

type EvaluateOption func(params Params)

func GeneratePreview

func GeneratePreview(enable bool) EvaluateOption

func IncludeCommandLineAPI

func IncludeCommandLineAPI(enable bool) EvaluateOption

func ReturnByValue

func ReturnByValue(enable bool) EvaluateOption

func Silent

func Silent(enable bool) EvaluateOption

func ThrowOnSideEffect

func ThrowOnSideEffect(enable bool) EvaluateOption

func UserGesture

func UserGesture(enable bool) EvaluateOption

type EventCallback

type EventCallback func(params Params)

EventCallback represents a callback function that handles DevTools protocol events. The callback receives event parameters as a Params map.

func ConsoleAPICallback

func ConsoleAPICallback(cb func([]interface{})) EventCallback

ConsoleAPICallback processes the Runtime.consolAPICalled event and returns printable info

type FetchRequestPattern

type FetchRequestPattern struct {
	UrlPattern   string       `json:"urlPattern,omitempty"`
	ResourceType ResourceType `json:"resourceType,omitempty"`
	RequestStage RequestStage `json:"requestStage,omitempty"`
}

type IdType

type IdType int
const (
	NodeId IdType = iota
	BackendNodeId
	ObjectId
)

type InterceptionStage

type InterceptionStage string

type KeyModifier

type KeyModifier int

type MouseEvent

type MouseEvent string

type MouseOption

type MouseOption func(p Params)

func Clicks

func Clicks(c int) MouseOption

func LeftButton

func LeftButton() MouseOption

func MiddleButton

func MiddleButton() MouseOption

func Modifiers

func Modifiers(m KeyModifier) MouseOption

func RightButton

func RightButton() MouseOption
type NavigationEntry struct {
	ID    int64  `json:"id"`    // Unique entry identifier
	URL   string `json:"url"`   // Page URL
	Title string `json:"title"` // Page title
}

NavigationEntry represents a navigation history entry. These entries make up the browser's navigation history for a tab.

type NavigationError string

NavigationError represents an error that occurred during page navigation.

func (err NavigationError) Error() string

Error implements the error interface for NavigationError.

type NavigationResponse string

NavigationResponse defines the type for ProcessNavigation `response`

type Params

type Params map[string]interface{}

Params is a type alias for the event parameters structure. It provides convenient methods to access parameter values of different types.

func (Params) Bool

func (p Params) Bool(k string) bool

Bool returns the boolean value for the given key. Returns false if the key doesn't exist or the value is not a boolean.

func (Params) Int

func (p Params) Int(k string) int

Int returns the integer value for the given key. Returns 0 if the key doesn't exist or the value cannot be converted to an integer.

func (Params) Map

func (p Params) Map(k string) map[string]interface{}

Map returns the map value for the given key. Returns nil if the key doesn't exist or the value is not a map.

func (Params) String

func (p Params) String(k string) string

String returns the string value for the given key. Returns an empty string if the key doesn't exist or the value is not a string.

type PrintToPDFOption

type PrintToPDFOption func(map[string]interface{})

PrintToPDFOption defines the functional option for PrintToPDF

func Dimensions

func Dimensions(width, height float64) PrintToPDFOption

Dimensions sets the current page dimensions for PrintToPDF

func DisplayHeaderFooter

func DisplayHeaderFooter() PrintToPDFOption

DisplayHeaderFooter instructs PrintToPDF to print headers/footers or not

func LandscapeMode

func LandscapeMode() PrintToPDFOption

LandscapeMode instructs PrintToPDF to print pages in landscape mode

func Margins

func Margins(top, bottom, left, right float64) PrintToPDFOption

Margins sets the margin sizes for PrintToPDF

func PageRanges

func PageRanges(ranges string) PrintToPDFOption

PageRanges instructs PrintToPDF to print only the specified range of pages

func PortraitMode

func PortraitMode() PrintToPDFOption

PortraitMode instructs PrintToPDF to print pages in portrait mode

func PrintBackground

func PrintBackground() PrintToPDFOption

printBackground instructs PrintToPDF to print background graphics

func Scale

func Scale(n float64) PrintToPDFOption

Scale instructs PrintToPDF to scale the pages (1.0 is current scale)

type Profile

type Profile struct {
	Nodes      []ProfileNode `json:"nodes"`      // Function call nodes
	StartTime  int64         `json:"startTime"`  // Profile start timestamp (microseconds)
	EndTime    int64         `json:"endTime"`    // Profile end timestamp (microseconds)
	Samples    []int64       `json:"samples"`    // Thread samples
	TimeDeltas []int64       `json:"timeDeltas"` // Time intervals between samples
}

Profile represents a JavaScript CPU profile. This structure contains detailed information about JavaScript execution.

type ProfileNode

type ProfileNode struct {
	ID            int64           `json:"id"`            // Unique node identifier
	CallFrame     json.RawMessage `json:"callFrame"`     // Function call frame
	HitCount      int64           `json:"hitCount"`      // Number of samples where this node was on top
	Children      []int64         `json:"children"`      // Child node IDs
	DeoptReason   string          `json:"deoptReason"`   // Deoptimization reason
	PositionTicks json.RawMessage `json:"positionTicks"` // Source positions where the function spent time
}

ProfileNode represents a node in the JavaScript CPU profile tree. Each node typically represents a function call in the program. The experimental fields are kept as json.RawMessage, so you may decode them with your own code. See: https://chromedevtools.github.io/debugger-protocol-viewer/tot/Profiler/

type RemoteDebugger

type RemoteDebugger struct {
	sync.Mutex // Mutex for thread safety
	// contains filtered or unexported fields
}

RemoteDebugger implements an interface for Chrome DevTools Protocol. It manages the connection to a Chrome instance and provides methods to control and interact with the browser through the DevTools Protocol.

func Connect

func Connect(port string, verbose bool, options ...ConnectOption) (*RemoteDebugger, error)

Connect to the remote debugger and return `RemoteDebugger` object. Connect establishes a connection to a Chrome instance's debugging port. The port parameter should be in the format "host:port" (e.g. "localhost:9222"). If verbose is true, additional debug information will be logged.

Example:

debugger, err := godet.Connect("localhost:9222", true)
if err != nil {
    log.Fatal(err)
}
defer debugger.Close()

func (*RemoteDebugger) ActivateTab

func (remote *RemoteDebugger) ActivateTab(tab *Tab) error

ActivateTab activates the specified tab.

func (*RemoteDebugger) AllEvents

func (remote *RemoteDebugger) AllEvents(enable bool) error

AllEvents enables event listening for all domains.

func (*RemoteDebugger) AttachToTarget

func (remote *RemoteDebugger) AttachToTarget(targetId string) (string, error)

Attaches to the target with given id.

func (*RemoteDebugger) CallbackEvent

func (remote *RemoteDebugger) CallbackEvent(method string, cb EventCallback)

CallbackEvent registers a callback function for a specific event type. The callback will be invoked whenever an event of the specified type is received.

Example:

debugger.CallbackEvent("Network.requestWillBeSent", func(params Params) {
    fmt.Printf("Request to: %s\n", params.String("request.url"))
})

func (*RemoteDebugger) CaptureScreenshot

func (remote *RemoteDebugger) CaptureScreenshot(format string, quality int, fromSurface bool) ([]byte, error)

CaptureScreenshot takes a screenshot of the current page. The format parameter can be "png" or "jpeg". If empty, "png" is used. The quality parameter (0-100) is only used for JPEG format. If fromSurface is true, the screenshot will be taken from the surface rather than the view.

Example:

data, err := debugger.CaptureScreenshot("png", 100, false)
if err != nil {
    log.Fatal(err)
}
ioutil.WriteFile("screenshot.png", data, 0644)

func (*RemoteDebugger) ClearBrowserCache

func (remote *RemoteDebugger) ClearBrowserCache() error

func (*RemoteDebugger) ClearBrowserCookies

func (remote *RemoteDebugger) ClearBrowserCookies() error

func (*RemoteDebugger) Close

func (remote *RemoteDebugger) Close() (err error)

Close terminates the connection to the Chrome instance. After calling Close, no further method calls should be made on the RemoteDebugger.

func (*RemoteDebugger) CloseBrowser

func (remote *RemoteDebugger) CloseBrowser()

CloseBrowser gracefully closes the browser we are connected to

func (*RemoteDebugger) CloseTab

func (remote *RemoteDebugger) CloseTab(tab *Tab) error

CloseTab closes the specified tab.

func (*RemoteDebugger) ContinueInterceptedRequest deprecated

func (remote *RemoteDebugger) ContinueInterceptedRequest(interceptionID string,
	errorReason ErrorReason,
	rawResponse string,
	url string,
	method string,
	postData string,
	headers map[string]string) error

ContinueInterceptedRequest is the response to Network.requestIntercepted which either modifies the request to continue with any modifications, or blocks it, or completes it with the provided response bytes.

If a network fetch occurs as a result which encounters a redirect an additional Network.requestIntercepted event will be sent with the same InterceptionId.

Parameters:

errorReason ErrorReason - if set this causes the request to fail with the given reason.
rawResponse string - if set the requests completes using with the provided base64 encoded raw response, including HTTP status line and headers etc...
url string - if set the request url will be modified in a way that's not observable by page.
method string - if set this allows the request method to be overridden.
postData string - if set this allows postData to be set.
headers Headers - if set this allows the request headers to be changed.

Deprecated: use ContinueRequest, FulfillRequest and FailRequest instead.

func (*RemoteDebugger) ContinueRequest

func (remote *RemoteDebugger) ContinueRequest(requestID string,
	url string,
	method string,
	postData string,
	headers map[string]string) error

ContinueRequest is the response to Fetch.requestPaused which either modifies the request to continue with any modifications, or blocks it, or completes it with the provided response bytes.

Parameters:

url string - if set the request url will be modified in a way that's not observable by page.
method string - if set this allows the request method to be overridden.
postData string - if set this allows postData to be set.
headers Headers - if set this allows the request headers to be changed.

func (*RemoteDebugger) DOMEvents

func (remote *RemoteDebugger) DOMEvents(enable bool) error

DOMEvents enables DOM events listening.

func (*RemoteDebugger) DebuggerEvents

func (remote *RemoteDebugger) DebuggerEvents(enable bool) error

DebuggerEvents enables Debugger events listening. When enabled, you can receive events about JavaScript execution, including: - Script parsing - Breakpoint hits - Exception throws

Example:

debugger.DebuggerEvents(true)
debugger.CallbackEvent("Debugger.paused", func(params Params) {
    fmt.Println("Execution paused at breakpoint")
})

func (*RemoteDebugger) DebuggerPause

func (remote *RemoteDebugger) DebuggerPause() error

func (*RemoteDebugger) DebuggerResume

func (remote *RemoteDebugger) DebuggerResume(terminateOnResume bool) error

func (*RemoteDebugger) DebuggerSetBreakpointsActive

func (remote *RemoteDebugger) DebuggerSetBreakpointsActive(active bool) error

func (*RemoteDebugger) DebuggerSkipAllPauses

func (remote *RemoteDebugger) DebuggerSkipAllPauses(skip bool) error

func (*RemoteDebugger) DeleteCookies

func (remote *RemoteDebugger) DeleteCookies(name, url, domain, path string) error

Deletes browser cookies with matching name and url or domain/path pair.

Parameters:

name string: Name of the cookies to remove. url string: If specified, deletes all the cookies with the given name where domain and path match provided URL. domain string: If specified, deletes only cookies with the exact domain. path string: If specified, deletes only cookies with the exact path.

func (*RemoteDebugger) DomainEvents

func (remote *RemoteDebugger) DomainEvents(domain string, enable bool) error

DomainEvents enables event listening in the specified domain.

func (*RemoteDebugger) EmulationEvents

func (remote *RemoteDebugger) EmulationEvents(enable bool) error

EmulationEvents enables Emulation events listening.

func (*RemoteDebugger) EnableRequestInterception

func (remote *RemoteDebugger) EnableRequestInterception(enabled bool) error

EnableRequestInterception enables interception, modification or cancellation of network requests. When enabled, all requests will be paused and need to be handled via ContinueInterceptedRequest.

Example:

debugger.EnableRequestInterception(true)
debugger.CallbackEvent("Network.requestIntercepted", func(params Params) {
    id := params.String("interceptionId")
    debugger.ContinueInterceptedRequest(id, "", "", "", "", "", nil)
})

func (*RemoteDebugger) EnableRequestPaused

func (remote *RemoteDebugger) EnableRequestPaused(enable bool, patterns ...FetchRequestPattern) error

EnableRequestPaused enables issuing of requestPaused events. A request will be paused until client calls one of failRequest, fulfillRequest or continueRequest/continueWithAuth.

If patterns is specified, only requests matching any of these patterns will produce fetchRequested event and will be paused until clients response. If not set,all requests will be affected.

func (*RemoteDebugger) Evaluate

func (remote *RemoteDebugger) Evaluate(expr string, options ...EvaluateOption) (interface{}, error)

Evaluate executes a JavaScript expression in the context of the current page. The expression result is returned as an interface{}. If the expression results in an error, an EvaluateError is returned.

Example:

result, err := debugger.Evaluate("document.title")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Page title: %v\n", result)

func (*RemoteDebugger) EvaluateWrap

func (remote *RemoteDebugger) EvaluateWrap(expr string, options ...EvaluateOption) (interface{}, error)

EvaluateWrap evaluates a list of expressions, EvaluateWrap wraps them in `(function(){ ... })()`. Use a return statement to return a value.

func (*RemoteDebugger) FailRequest

func (remote *RemoteDebugger) FailRequest(requestID string, errorReason ErrorReason) error

FailRequest causes the request to fail with specified reason.

func (*RemoteDebugger) FetchResponseBody

func (remote *RemoteDebugger) FetchResponseBody(requestId string) ([]byte, error)

func (*RemoteDebugger) Focus

func (remote *RemoteDebugger) Focus(nodeID int) error

Focus sets focus on a specified node.

func (*RemoteDebugger) FulfillRequest

func (remote *RemoteDebugger) FulfillRequest(requestID string, responseCode int, responsePhrase string, headers map[string]string, body []byte) error

FulfillRequest provides a response to the request.

func (*RemoteDebugger) GetAllCookies

func (remote *RemoteDebugger) GetAllCookies() ([]Cookie, error)

GetAllCookies returns all browser cookies. Depending on the backend support, will return detailed cookie information in the `cookies` field.

func (*RemoteDebugger) GetBoxModel

func (remote *RemoteDebugger) GetBoxModel(nodeID int) (map[string]interface{}, error)

GetBoxModel returns boxes for a DOM node identified by nodeId.

func (*RemoteDebugger) GetCertificate

func (remote *RemoteDebugger) GetCertificate(origin string) ([]string, error)

func (*RemoteDebugger) GetComputedStyleForNode

func (remote *RemoteDebugger) GetComputedStyleForNode(nodeID int) (map[string]interface{}, error)

GetComputedStyleForNode returns the computed style for a DOM node identified by nodeId.

func (*RemoteDebugger) GetCookies

func (remote *RemoteDebugger) GetCookies(urls []string) ([]Cookie, error)

GetCookies returns all browser cookies for the specified URLs. If urls is nil, returns all cookies for all URLs.

Example:

cookies, err := debugger.GetCookies([]string{"https://example.com"})
if err != nil {
    log.Fatal(err)
}
for _, cookie := range cookies {
    fmt.Printf("Cookie: %s = %s\n", cookie.Name, cookie.Value)
}

func (*RemoteDebugger) GetDocument

func (remote *RemoteDebugger) GetDocument() (map[string]interface{}, error)

GetDocument gets the "Document" object as a DevTool node.

func (*RemoteDebugger) GetDomains deprecated

func (remote *RemoteDebugger) GetDomains() ([]Domain, error)

GetDomains lists the available DevTools domains.

Deprecated: The Schema domain is now deprecated.

func (*RemoteDebugger) GetNavigationHistory

func (remote *RemoteDebugger) GetNavigationHistory() (int, []NavigationEntry, error)

GetNavigationHistory returns navigation history for the current page.

func (*RemoteDebugger) GetOuterHTML

func (remote *RemoteDebugger) GetOuterHTML(nodeID int) (string, error)

GetOuterHTML returns node's HTML markup.

func (*RemoteDebugger) GetPreciseCoverage

func (remote *RemoteDebugger) GetPreciseCoverage(precise bool) ([]interface{}, error)

GetPreciseCoverage collects coverage data for the current isolate and resets execution counters.

func (*RemoteDebugger) GetResponseBody

func (remote *RemoteDebugger) GetResponseBody(req string) ([]byte, error)

GetResponseBody returns the response body of a given requestId (from the Network.responseReceived payload). The response body can be base64 encoded if the response is binary.

Example:

debugger.CallbackEvent("Network.responseReceived", func(params Params) {
    reqID := params.String("requestId")
    body, err := debugger.GetResponseBody(reqID)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Response body: %s\n", body)
})

func (*RemoteDebugger) GetResponseBodyForInterception

func (remote *RemoteDebugger) GetResponseBodyForInterception(iid string) ([]byte, error)

func (*RemoteDebugger) GetScriptSource

func (remote *RemoteDebugger) GetScriptSource(id string) (string, error)

func (*RemoteDebugger) GetTargets

func (remote *RemoteDebugger) GetTargets() (map[string]interface{}, error)

Retrieves a list of available targets.

func (*RemoteDebugger) HandleJavaScriptDialog

func (remote *RemoteDebugger) HandleJavaScriptDialog(accept bool, promptText string) error

HandleJavaScriptDialog accepts or dismisses a Javascript initiated dialog.

func (*RemoteDebugger) LogEvents

func (remote *RemoteDebugger) LogEvents(enable bool) error

LogEvents enables Log events listening.

func (*RemoteDebugger) MouseEvent

func (remote *RemoteDebugger) MouseEvent(ev MouseEvent, x, y int, options ...MouseOption) error

MouseEvent dispatches a mouse event to the page. An event can be MouseMove, MousePressed and MouseReleased. An event always requires mouse coordinates, while other parameters are optional.

To simulate mouse button presses, pass LeftButton()/RightButton()/MiddleButton() options and possibily key modifiers. It is also possible to pass the number of clicks (2 for double clicks, etc.).

func (*RemoteDebugger) Navigate

func (remote *RemoteDebugger) Navigate(url string) (string, error)

Navigate causes the browser to navigate to the specified URL. Returns the frame ID that will be navigated.

Example:

frameID, err := debugger.Navigate("https://example.com")
if err != nil {
    log.Fatal(err)
}

func (*RemoteDebugger) NavigateTransition

func (remote *RemoteDebugger) NavigateTransition(url string, trans TransitionType) (string, error)

func (*RemoteDebugger) NetworkEvents

func (remote *RemoteDebugger) NetworkEvents(enable bool) error

NetworkEvents enables Network events listening. When enabled, you can receive events about network traffic, including: - Network requests and responses - WebSocket traffic - Resource loading

Example:

debugger.NetworkEvents(true)
debugger.CallbackEvent("Network.requestWillBeSent", func(params Params) {
    fmt.Printf("Request to: %s\n", params.String("request.url"))
})

func (*RemoteDebugger) NewTab

func (remote *RemoteDebugger) NewTab(url string) (*Tab, error)

NewTab creates a new tab.

func (*RemoteDebugger) PageEvents

func (remote *RemoteDebugger) PageEvents(enable bool) error

PageEvents enables Page events listening.

func (*RemoteDebugger) PrintToPDF

func (remote *RemoteDebugger) PrintToPDF(options ...PrintToPDFOption) ([]byte, error)

PrintToPDF print the current page as PDF.

func (*RemoteDebugger) ProcessNavigation

func (remote *RemoteDebugger) ProcessNavigation(navigationID int, navigation NavigationResponse) error

ProcessNavigation should be sent in response to a navigationRequested or a redirectRequested event, telling the browser how to handle the navigation.

func (*RemoteDebugger) ProfilerEvents

func (remote *RemoteDebugger) ProfilerEvents(enable bool) error

ProfilerEvents enables Profiler events listening.

func (*RemoteDebugger) Protocol

func (remote *RemoteDebugger) Protocol() (map[string]interface{}, error)

Protocol returns the DevTools protocol specification

func (*RemoteDebugger) QuerySelector

func (remote *RemoteDebugger) QuerySelector(nodeID int, selector string) (map[string]interface{}, error)

QuerySelector gets the nodeId for a specified selector.

func (*RemoteDebugger) QuerySelectorAll

func (remote *RemoteDebugger) QuerySelectorAll(nodeID int, selector string) (map[string]interface{}, error)

QuerySelectorAll gets a list of nodeId for the specified selectors.

func (*RemoteDebugger) Reload

func (remote *RemoteDebugger) Reload() error

Reload reloads the current page.

func (*RemoteDebugger) RequestNode

func (remote *RemoteDebugger) RequestNode(nodeID int) error

RequestNode requests a node, the response is generated as a DOM.setChildNodes event.

func (*RemoteDebugger) ResolveNode

func (remote *RemoteDebugger) ResolveNode(nodeID int) (map[string]interface{}, error)

ResolveNode returns some information about the node.

func (*RemoteDebugger) RuntimeEvents

func (remote *RemoteDebugger) RuntimeEvents(enable bool) error

RuntimeEvents enables Runtime events listening.

func (*RemoteDebugger) SavePDF

func (remote *RemoteDebugger) SavePDF(filename string, perm os.FileMode, options ...PrintToPDFOption) error

SavePDF print current page as PDF and save to file

func (*RemoteDebugger) SaveScreenshot

func (remote *RemoteDebugger) SaveScreenshot(filename string, perm os.FileMode, quality int, fromSurface bool) error

SaveScreenshot takes a screenshot and saves it directly to a file. The file format is determined by the filename extension (.png or .jpg). The quality parameter (0-100) is only used for JPEG format. If fromSurface is true, the screenshot will be taken from the surface rather than the view.

Example:

err := debugger.SaveScreenshot("screenshot.png", 0644, 100, false)
if err != nil {
    log.Fatal(err)
}

func (*RemoteDebugger) SendRequest

func (remote *RemoteDebugger) SendRequest(method string, params Params) (map[string]interface{}, error)

SendRequest sends a request and returns the reply as a a map.

func (*RemoteDebugger) SendRune

func (remote *RemoteDebugger) SendRune(c rune) error

SendRune sends a character as keyboard input.

func (*RemoteDebugger) ServiceWorkerEvents

func (remote *RemoteDebugger) ServiceWorkerEvents(enable bool) error

ServiceWorkerEvents enables ServiceWorker events listening.

func (*RemoteDebugger) SetAttributeValue

func (remote *RemoteDebugger) SetAttributeValue(nodeID int, name, value string) error

SetAttributeValue sets the value for a specified attribute.

func (*RemoteDebugger) SetAutoAttach

func (remote *RemoteDebugger) SetAutoAttach(autoAttach bool) error

Controls whether to automatically attach to new targets which are considered to be related to this one. When turned on, attaches to all existing related targets as well. When turned off, automatically detaches from all currently attached targets. This also clears all targets added by `autoAttachRelated` from the list of targets to watch for creation of related targets.",

func (*RemoteDebugger) SetBlockedURLs

func (remote *RemoteDebugger) SetBlockedURLs(urls ...string) error

SetBlockedURLs blocks URLs from loading (wildcards '*' are allowed). This can be used to block specific resources or entire domains.

Example:

// Block all tracking scripts
debugger.SetBlockedURLs("*google-analytics.com*", "*doubleclick.net*")

func (*RemoteDebugger) SetBypassServiceWorker

func (remote *RemoteDebugger) SetBypassServiceWorker(bypass bool) error

SetBypassServiceWorker toggles ignoring of service worker for each request

func (*RemoteDebugger) SetCacheDisabled

func (remote *RemoteDebugger) SetCacheDisabled(disabled bool) error

SetCacheDisabled toggles ignoring cache for each request. If true, cache will not be used and each request will be sent to the server.

Example:

debugger.SetCacheDisabled(true) // Disable cache
debugger.Navigate("https://example.com") // This will bypass cache

func (*RemoteDebugger) SetControlNavigations

func (remote *RemoteDebugger) SetControlNavigations(enabled bool) error

SetControlNavigations toggles navigation throttling which allows programatic control over navigation and redirect response.

func (*RemoteDebugger) SetCookie

func (remote *RemoteDebugger) SetCookie(cookie Cookie) bool

Set browser cookie

func (*RemoteDebugger) SetCookies

func (remote *RemoteDebugger) SetCookies(cookies []Cookie) error

SetCookies sets browser cookies for the current page.

Example:

err := debugger.SetCookies([]Cookie{
    {
        Name: "session",
        Value: "abc123",
        Domain: "example.com",
        Path: "/",
    },
})

func (*RemoteDebugger) SetDeviceMetricsOverride

func (remote *RemoteDebugger) SetDeviceMetricsOverride(width int, height int, deviceScaleFactor float64, mobile bool, fitWindow bool) error

SetDeviceMetricsOverride sets mobile and fitWindow on top of device dimensions Can be used to produce screenshots of mobile viewports.

func (*RemoteDebugger) SetDiscoverTargets

func (remote *RemoteDebugger) SetDiscoverTargets(discover bool) error

Controls whether to discover available targets and notify via `targetCreated/targetInfoChanged/targetDestroyed` events."

func (*RemoteDebugger) SetDownloadBehavior

func (remote *RemoteDebugger) SetDownloadBehavior(behavior DownloadBehavior, downloadPath string) error

SetDownloadBehaviour enable/disable downloads.

func (*RemoteDebugger) SetFileInputFiles

func (remote *RemoteDebugger) SetFileInputFiles(id int, files []string, idType IdType) error

SetFileInputFiles sets files for the given file input element.

func (*RemoteDebugger) SetInputFiles

func (remote *RemoteDebugger) SetInputFiles(nodeID int, files []string) error

SetInputFiles attaches input files to a specified node (an input[type=file] element?). Note: this has been renamed SetFileInputFiles

func (*RemoteDebugger) SetOuterHTML

func (remote *RemoteDebugger) SetOuterHTML(nodeID int, outerHTML string) error

SetOuterHTML sets node HTML markup.

func (*RemoteDebugger) SetProfilerSamplingInterval

func (remote *RemoteDebugger) SetProfilerSamplingInterval(n int64) error

SetProfilerSamplingInterval sets the profiler sampling interval in microseconds, must be called before StartProfiler.

func (*RemoteDebugger) SetRequestInterception deprecated

func (remote *RemoteDebugger) SetRequestInterception(patterns ...RequestPattern) error

SetRequestInterception sets the requests to intercept that match the provided patterns and optionally resource types.

Example:

debugger.SetRequestInterception(RequestPattern{
    UrlPattern: "*",
    ResourceType: ResourceTypeDocument,
    InterceptionStage: StageRequest,
})

Deprecated: use EnableRequestPaused instead.

func (*RemoteDebugger) SetScriptSource

func (remote *RemoteDebugger) SetScriptSource(id, source string) error

func (*RemoteDebugger) SetUserAgent

func (remote *RemoteDebugger) SetUserAgent(userAgent string) error

SetUserAgent overrides the default user agent. This affects all subsequent network requests.

Example:

debugger.SetUserAgent("Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X)")

func (*RemoteDebugger) SetVirtualTimePolicy

func (remote *RemoteDebugger) SetVirtualTimePolicy(policy VirtualTimePolicy, budget int, options ...setVirtualTimerPolicyOption) error

SetVirtualTimePolicy turns on virtual time for all frames (replacing real-time with a synthetic time source) and sets the current virtual time policy. Note this supersedes any previous time budget.

func (*RemoteDebugger) SetVisibleSize deprecated

func (remote *RemoteDebugger) SetVisibleSize(width, height int) error

SetVisibleSize resizes the frame/viewport of the page. Note that this does not affect the frame's container (e.g. browser window). Can be used to produce screenshots of the specified size.

Deprecated: Emulation.setVisibleSize is now deprecated.

func (*RemoteDebugger) StartPreciseCoverage

func (remote *RemoteDebugger) StartPreciseCoverage(callCount, detailed bool) error

StartPreciseCoverage enable precise code coverage.

func (*RemoteDebugger) StartProfiler

func (remote *RemoteDebugger) StartProfiler() error

StartProfiler starts the profiler.

func (*RemoteDebugger) StopPreciseCoverage

func (remote *RemoteDebugger) StopPreciseCoverage() error

StopPreciseCoverage disable precise code coverage.

func (*RemoteDebugger) StopProfiler

func (remote *RemoteDebugger) StopProfiler() (p Profile, err error)

StopProfiler stops the profiler. Returns a Profile data structure, as specified here: https://chromedevtools.github.io/debugger-protocol-viewer/tot/Profiler/#type-Profile

func (*RemoteDebugger) TabList

func (remote *RemoteDebugger) TabList(filter string) ([]*Tab, error)

TabList returns a list of opened tabs/pages. If filter is not empty, only tabs of the specified type are returned (i.e. "page").

Note that tabs are ordered by activitiy time (most recently used first) so the current tab is the first one of type "page".

func (*RemoteDebugger) TargetEvents

func (remote *RemoteDebugger) TargetEvents(enable bool) error

TargetEvents enables Target events listening.

func (*RemoteDebugger) Verbose

func (remote *RemoteDebugger) Verbose(v bool)

func (*RemoteDebugger) Version

func (remote *RemoteDebugger) Version() (*Version, error)

Version returns version information (protocol, browser, etc.).

type RequestPattern

type RequestPattern struct {
	UrlPattern        string            `json:"urlPattern,omitempty"`
	ResourceType      ResourceType      `json:"resourceType,omitempty"`
	InterceptionStage InterceptionStage `json:"interceptionStage,omitempty"`
}

type RequestStage

type RequestStage string

type ResourceType

type ResourceType string

type Tab

type Tab struct {
	ID          string `json:"id"`                   // Unique tab identifier
	Type        string `json:"type"`                 // Tab type (e.g., "page")
	Description string `json:"description"`          // Tab description
	Title       string `json:"title"`                // Page title
	URL         string `json:"url"`                  // Page URL
	WsURL       string `json:"webSocketDebuggerUrl"` // WebSocket URL for this tab
	DevURL      string `json:"devtoolsFrontendUrl"`  // DevTools frontend URL
}

Tab represents an opened tab/page in the browser. Each tab can be controlled independently through the DevTools protocol.

type TransitionType

type TransitionType string

type Version

type Version struct {
	Browser         string `json:"Browser"`          // Browser name and version
	ProtocolVersion string `json:"Protocol-Version"` // DevTools protocol version
	UserAgent       string `json:"User-Agent"`       // Browser's user agent
	V8Version       string `json:"V8-Version"`       // V8 engine version
	WebKitVersion   string `json:"WebKit-Version"`   // WebKit version
}

Version holds the DevTools version information. This structure is returned by the Version() method.

type VirtualTimePolicy

type VirtualTimePolicy string

VirtualTimePolicy defines the type for Emulation.SetVirtualTimePolicy

Directories

Path Synopsis
cmd
godet command
godship command

Jump to

Keyboard shortcuts

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