godet

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

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

Go to latest
Published: Jul 8, 2017 License: MIT Imports: 12 Imported by: 0

README

Go Documentation Go Report Card

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, _ := godet.Connect("localhost:9222", true)

// 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"

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

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

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

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

Functions

This section is empty.

Types

type Domain

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

Domain holds a domain name and version.

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 EventCallback

type EventCallback func(params Params)

EventCallback represents a callback event, associated with a method.

type NavigationEntry struct {
	ID    int64  `json:"id"`
	URL   string `json:"url"`
	Title string `json:"title"`
}

NavigationEntry represent a navigation history entry.

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

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

Connect to the remote debugger and return `RemoteDebugger` object.

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

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

CallbackEvent sets a callback for the specified event.

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

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

Close the RemoteDebugger connection.

func (*RemoteDebugger) CloseTab

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

CloseTab closes the specified tab.

func (*RemoteDebugger) ContinueInterceptedRequest

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.

func (*RemoteDebugger) DOMEvents

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

DOMEvents enables DOM events listening.

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

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

Evaluate evalutes a Javascript function in the context of the current page.

func (*RemoteDebugger) EvaluateWrap

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

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

func (*RemoteDebugger) Focus

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

Focus sets focus on a specified node.

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

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

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

func (*RemoteDebugger) GetDomains

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

GetDomains lists the available DevTools domains.

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

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

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

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

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

SetInputFiles attaches input files to a specified node (an input[type=file] element?).

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

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.

func (*RemoteDebugger) StartProfiler

func (remote *RemoteDebugger) StartProfiler() error

StartProfiler starts the profiler.

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

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

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

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