godet

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Aug 11, 2022 License: MIT Imports: 14 Imported by: 0

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.

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 (
	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 AddDebugger

func AddDebugger(targetId string, baseWsUrl string) error

func AddEventListener

func AddEventListener(method string, cb EventCallback)

AddEventListener add event handler to the service

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 StopCapture

func StopCapture()

StopCapture stop service

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)

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"`
	Value    string  `json:"value"`
	Domain   string  `json:"domain"`
	Path     string  `json:"path"`
	Size     int     `json:"size"`
	Expires  float64 `json:"expires"`
	HttpOnly bool    `json:"httpOnly"`
	Secure   bool    `json:"secure"`
	Session  bool    `json:"session"`
	SameSite string  `json:"sameSite"`
}

type Domain

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

Domain holds a domain name and version.

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{}
	ExceptionDetails map[string]interface{}
}

EvaluateError is returned by Evaluate in case of expression errors.

func (EvaluateError) Error

func (err EvaluateError) Error() string

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 event, associated with a method.

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"`
	URL   string `json:"url"`
	Title string `json:"title"`
}

NavigationEntry represent a navigation history entry.

type NavigationError string
func (err NavigationError) Error() string
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 params structure.

func (Params) Bool

func (p Params) Bool(k string) bool

func (Params) Float64

func (p Params) Float64(k string) float64

Float64 return the float value

func (Params) Int

func (p Params) Int(k string) int

func (Params) Map

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

func (Params) String

func (p Params) String(k string) 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"`
	StartTime  int64         `json:"startTime"`
	EndTime    int64         `json:"endTime"`
	Samples    []int64       `json:"samples"`
	TimeDeltas []int64       `json:"timeDeltas"`
}

Profile represents a profile data structure.

type ProfileNode

type ProfileNode struct {
	ID            int64           `json:"id"`
	CallFrame     json.RawMessage `json:"callFrame"`
	HitCount      int64           `json:"hitCount"`
	Children      []int64         `json:"children"`
	DeoptReason   string          `json:"deoptReason"`
	PositionTicks json.RawMessage `json:"positionTicks"`
}

ProfileNode represents a profile node data structure. 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
	// contains filtered or unexported fields
}

RemoteDebugger implements an interface for Chrome DevTools.

func StartCapture

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

StartCapture 连接当前活跃tab页,并开始接收消息

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) CaptureScreenshot

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

CaptureScreenshot takes a screenshot, uses "png" as default format.

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 the RemoteDebugger connection.

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) 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

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 evalutes a Javascript function in the context of the current page.

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 current URL. Depending on the backend support, will return detailed cookie information in the `cookies` field.

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).

func (*RemoteDebugger) GetResponseBodyForInterception

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

func (*RemoteDebugger) GetTitle

func (remote *RemoteDebugger) GetTitle(requestId string) string

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 navigates to the specified URL.

func (*RemoteDebugger) NetworkEvents

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

NetworkEvents enables Network events listening.

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 to a file.

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) SetBlockedURLs

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

SetBlockedURLs blocks URLs from loading (wildcards '*' are allowed)

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.

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

Set browser cookies.

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) 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.

Deprecated: use EnableRequestPaused instead.

func (*RemoteDebugger) SetUserAgent

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

SetUserAgent overrides the default user agent.

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. Adding by aiwen

func (*RemoteDebugger) TargetId

func (remote *RemoteDebugger) TargetId() string

TargetId return the target ID associate with the Connection

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"`
	Type        string `json:"type"`
	Description string `json:"description"`
	Title       string `json:"title"`
	URL         string `json:"url"`
	WsURL       string `json:"webSocketDebuggerUrl"`
	DevURL      string `json:"devtoolsFrontendUrl"`
}

Tab represents an opened tab/page.

type Version

type Version struct {
	Browser         string `json:"Browser"`
	ProtocolVersion string `json:"Protocol-Version"`
	UserAgent       string `json:"User-Agent"`
	V8Version       string `json:"V8-Version"`
	WebKitVersion   string `json:"WebKit-Version"`
}

Version holds the DevTools version information.

type VirtualTimePolicy

type VirtualTimePolicy string

VirtualTimePolicy defines the type for Emulation.SetVirtualTimePolicy

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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