gcd

package module
v1.0.15 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2020 License: MIT Imports: 20 Imported by: 12

README

Go Report Card

Google Chrome Debugger (GCD)

This is primarly an auto-generated client library for communicating with a Google Chrome Browser over their remote client debugger protocol. Note that their documentation is partially incorrect and does not contain a lot of the API calls that are actually available.

Because I'm lazy and there are hundereds of different custom types and API methods, this library has been automatically generated using their protocol.json.

The gcdapigen program was created to generate types, event types and commands for gcd.

Changelog

See the CHANGELOG.

Dependencies

gcd requires the gcdapi and gcdmessage packages. gcdapi is the auto-generated API. gcdmessage is the glue between gcd and gcdapi so we can keep the packages clean.

The API

The API consists of of synchronous requests, asynchronous requests / events. Synchronous requests are handled by using non-buffered channels and methods can be called and will return once the value is available. Events are handled by subscribing the response method type and calling the API's "Enable()" such as:

    target, err := debugger.NewTab()
    if err != nil {
    	log.Fatalf("error getting new tab: %s\n", err)
	}
	console := target.Console

	target.Subscribe("Console.messageAdded", func(target *ChromeTarget, v []byte) {
		
		msg := &gcdapi.ConsoleMessageAddedEvent{}
		err := json.Unmarshal(v, msg)
		if err != nil {
			log.Fatalf("error unmarshalling event data: %v\n", err)
		}
		log.Printf("METHOD: %s\n", msg.Method)
		eventData := msg.Params.Message
		log.Printf("Got event: %s\n", eventData)
	})
	console.Enable()
	// recv events
	// console.Disable()

Usage

For a full list of api methods, types, event types & godocs: Documentation

Examples

See examples

Licensing

The MIT License (MIT)

Copyright (c) 2018 isaac dawson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNoTabAvailable = errors.New("no available tab found")
)
View Source
var GCDVERSION = "v1.0.15"

Functions

This section is empty.

Types

type ChromeTarget

type ChromeTarget struct {

	// Chrome Debugger Domains
	Accessibility        *gcdapi.Accessibility
	Animation            *gcdapi.Animation
	ApplicationCache     *gcdapi.ApplicationCache // application cache API
	Audits               *gcdapi.Audits
	BackgroundService    *gcdapi.BackgroundService
	Browser              *gcdapi.Browser
	CacheStorage         *gcdapi.CacheStorage
	Cast                 *gcdapi.Cast
	Console              *gcdapi.Console           // console API
	CSS                  *gcdapi.CSS               // CSS API
	Database             *gcdapi.Database          // Database API
	Debugger             *gcdapi.Debugger          // JS Debugger API
	DeviceOrientation    *gcdapi.DeviceOrientation // Device Orientation API
	DOM                  *gcdapi.DOM               // DOM API
	DOMDebugger          *gcdapi.DOMDebugger       // DOM Debugger API
	DOMSnapshot          *gcdapi.DOMSnapshot
	DOMStorage           *gcdapi.DOMStorage // DOM Storage API
	Emulation            *gcdapi.Emulation
	Fetch                *gcdapi.Fetch
	HeadlessExperimental *gcdapi.HeadlessExperimental
	HeapProfiler         *gcdapi.HeapProfiler // HeapProfiler API
	IndexedDB            *gcdapi.IndexedDB    // IndexedDB API
	Input                *gcdapi.Input        // Why am i doing this, it's obvious what they are, I quit.
	Inspector            *gcdapi.Inspector
	IO                   *gcdapi.IO
	LayerTree            *gcdapi.LayerTree
	Log                  *gcdapi.Log
	Memory               *gcdapi.Memory
	Network              *gcdapi.Network
	Overlay              *gcdapi.Overlay
	Page                 *gcdapi.Page
	Performance          *gcdapi.Performance // if stable channel you'll need to uncomment
	Profiler             *gcdapi.Profiler
	Runtime              *gcdapi.Runtime
	Schema               *gcdapi.Schema
	Security             *gcdapi.Security
	ServiceWorker        *gcdapi.ServiceWorker
	Storage              *gcdapi.Storage
	SystemInfo           *gcdapi.SystemInfo
	TargetApi            *gcdapi.Target // buh name collision
	Tracing              *gcdapi.Tracing
	Tethering            *gcdapi.Tethering
	Media                *gcdapi.Media
	WebAudio             *gcdapi.WebAudio
	WebAuthn             *gcdapi.WebAuthn

	Target *TargetInfo // The target information see, TargetInfo
	// contains filtered or unexported fields
}

ChromeTarget (Tab/Process). Messages are returned to callers via non-buffered channels. Helpfully, the remote debugger service uses id's so we can correlate which request should match which response. We use a map to store the id of the request which contains a reference to a gcdmessage.Message that holds the reply channel for the ChromeTarget to return the response to. Events are handled by mapping the method name to a function which takes a target and byte output. For now, callers will need to unmarshall the types themselves.

func (*ChromeTarget) Debug

func (c *ChromeTarget) Debug(debug bool)

Debug for printing various debug information

func (*ChromeTarget) DebugEvents

func (c *ChromeTarget) DebugEvents(debug bool)

DebugEvents to print out raw JSON event data when not Subscribed.

func (*ChromeTarget) GetApiTimeout

func (c *ChromeTarget) GetApiTimeout() time.Duration

GetApiTimeout used by gcdmessage.SendCustomReturn and gcdmessage.SendDefaultRequest to timeout an API call if chrome hasn't responded to us in apiTimeout time.

func (*ChromeTarget) GetDoneCh

func (c *ChromeTarget) GetDoneCh() chan struct{}

GetDoneCh channel used to signal any pending SendDefaultRequest and SendCustomReturn that we are exiting so we don't block goroutines from exiting.

func (*ChromeTarget) GetId

func (c *ChromeTarget) GetId() int64

GetId increments the Id so we can synchronize our request/responses internally

func (*ChromeTarget) GetSendCh

func (c *ChromeTarget) GetSendCh() chan *gcdmessage.Message

GetSendCh the channel used for API components to send back to use

func (*ChromeTarget) Init

func (c *ChromeTarget) Init()

Init all api objects

func (*ChromeTarget) SetApiTimeout

func (c *ChromeTarget) SetApiTimeout(timeout time.Duration)

SetApiTimeout for how long we should wait before giving up gcdmessages. In the highly unusable (but it has occurred) event that chrome does not respond to one of our messages, we should be able to return from gcdmessage functions.

func (*ChromeTarget) Subscribe

func (c *ChromeTarget) Subscribe(method string, callback func(*ChromeTarget, []byte))

Subscribe Events, you must know the method name, such as Page.loadFiredEvent, and bind a function which takes a ChromeTarget (us) and the raw JSON byte data for that event.

func (*ChromeTarget) Unsubscribe

func (c *ChromeTarget) Unsubscribe(method string)

Unsubscribe the handler for no longer receiving events.

type Gcd

type Gcd struct {
	// contains filtered or unexported fields
}

The Google Chrome Debugger

func NewChromeDebugger

func NewChromeDebugger() *Gcd

Give it a friendly name.

func (*Gcd) ActivateTab

func (c *Gcd) ActivateTab(target *ChromeTarget) error

ActivateTab (focus) the tab.

func (*Gcd) AddEnvironmentVars

func (c *Gcd) AddEnvironmentVars(vars []string)

AddEnvironmentVars for the chrome process, useful for Xvfb etc.

func (*Gcd) AddFlags

func (c *Gcd) AddFlags(flags []string)

AddFlags Allows caller to add additional startup flags to the chrome process

func (*Gcd) CloseTab

func (c *Gcd) CloseTab(target *ChromeTarget) error

CloseTab closes the target tab.

func (*Gcd) ConnectToInstance

func (c *Gcd) ConnectToInstance(host string, port string) error

ConnectToInstance connects to a running chrome instance without starting a local process Host - The host destination. Port - The port to listen on.

func (*Gcd) DeleteProfileOnExit added in v1.0.1

func (c *Gcd) DeleteProfileOnExit()

func (*Gcd) ExitProcess

func (c *Gcd) ExitProcess() error

ExitProcess kills the process

func (*Gcd) GetFirstTab added in v1.0.1

func (c *Gcd) GetFirstTab() (*ChromeTarget, error)

GetFirstTab returns the first tab created, to be called when first started, otherwise you will get a random tab returned.

func (*Gcd) GetNewTargets

func (c *Gcd) GetNewTargets(knownIds map[string]struct{}) ([]*ChromeTarget, error)

GetNewTargets gets a list of current tabs and creates new chrome targets returning a list provided they weren't in the knownIds list. Note it is an error to attempt to create a new chrome target from one that already exists.

func (*Gcd) GetRevision

func (c *Gcd) GetRevision() string

GetRevision of chrome

func (*Gcd) GetTargets

func (c *Gcd) GetTargets() ([]*ChromeTarget, error)

GetTargets primary tabs/processes to work with. Each will have their own references to the underlying API components (such as Page, Debugger, DOM etc).

func (*Gcd) Host added in v1.0.5

func (c *Gcd) Host() string

Host that the debugger is listening on

func (*Gcd) NewTab

func (c *Gcd) NewTab() (*ChromeTarget, error)

NewTab a new empty tab, returns the chrome target.

func (*Gcd) PID added in v1.0.3

func (c *Gcd) PID() int

PID of the started process

func (*Gcd) Port added in v1.0.5

func (c *Gcd) Port() string

Port that the debugger is listening on

func (*Gcd) SetTerminationHandler

func (c *Gcd) SetTerminationHandler(handler TerminatedHandler)

Pass a handler to be notified when the chrome process exits.

func (*Gcd) SetTimeout

func (c *Gcd) SetTimeout(timeout time.Duration)

SetTimeout for how long we should wait for debug port to become available.

func (*Gcd) StartProcess

func (c *Gcd) StartProcess(exePath, userDir, port string) error

StartProcess the process exePath - the path to the executable userDir - the user directory to start from so we get a fresh profile port - The port to listen on.

func (*Gcd) StartProcessCustom added in v1.0.3

func (c *Gcd) StartProcessCustom(cmd *exec.Cmd, userDir, port string) error

StartProcessCustom lets you pass in the exec.Cmd to use

type GcdBodyReadErr

type GcdBodyReadErr struct {
	Message string
}

When we get an error reading the body from the debugger api endpoint

func (*GcdBodyReadErr) Error

func (g *GcdBodyReadErr) Error() string

type GcdDecodingErr

type GcdDecodingErr struct {
	Message string
}

Failure to unmarshal the JSON response from debugger API

func (*GcdDecodingErr) Error

func (g *GcdDecodingErr) Error() string

type TargetInfo

type TargetInfo struct {
	Description          string `json:"description"`
	DevtoolsFrontendUrl  string `json:"devtoolsFrontendUrl"`
	FaviconUrl           string `json:"faviconUrl"`
	Id                   string `json:"id"`
	Title                string `json:"title"`
	Type                 string `json:"type"`
	Url                  string `json:"url"`
	WebSocketDebuggerUrl string `json:"webSocketDebuggerUrl"`
}

TargetInfo defines the 'tab' or target for this chrome instance, can be multiple and background processes are included (not just visual tabs)

type TerminatedHandler

type TerminatedHandler func(reason string)

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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