cri

package module
v0.0.0-...-7af6ec4 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2017 License: Unlicense Imports: 11 Imported by: 0

README

cri - chrome remote interface

GoDoc Go Report Card Go Report Card

Package cri provides type-safe bindings for devtools protocol. It can be used with Chrome or any other target that implements the interface.

Protocol is generated by cmd/generate.sh. Script fetches latest version of protocol and generates types and domain (accessibility, domdebugger, performance etc.) packages. Master branch reflects tip of tree.

Tested with go1.4 and above.

Install
go get -u github.com/SKatiyar/cri
Usage

Taking a screenshot.

package main

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
  
	"github.com/SKatiyar/cri"
	"github.com/SKatiyar/cri/browser"
	"github.com/SKatiyar/cri/page"
)

func main() {
	conn, connErr := cri.NewConnection()
	if connErr != nil {
		fmt.Println(connErr)
		return
	}

	res, resErr := browser.New(conn).GetVersion()
	if resErr != nil {
		fmt.Println(resErr)
		return
	}

	pi := page.New(conn)
	if enableErr := pi.Enable(); enableErr != nil {
		fmt.Println(enableErr)
		return
	}

	nav, navErr := pi.Navigate(&page.NavigateRequest{
		Url: "https://www.example.com",
	})
	if navErr != nil {
		fmt.Println(navErr)
		return
	}

	pic, picErr := pi.CaptureScreenshot(nil)
	if picErr != nil {
		fmt.Println(picErr)
		return
	}

	img, imgErr := base64.StdEncoding.DecodeString(pic.Data)
	if imgErr != nil {
		fmt.Println(imgErr)
		return
	}

	if writeErr := ioutil.WriteFile("img.png", img, 0700); writeErr != nil {
		fmt.Println(writeErr)
		return
	}

	fmt.Println(res.JsVersion, nav.FrameId)
}

TODO
  • Add go get support to version 1.2 of protocol.
  • Add tests for connection.go
  • Add tests for domain packages.
  • Simplify On function.
  • Add timeout to On function.

Documentation

Overview

Package cri provides type-safe bindings for devtools protocol, and can be used with Chrome or any other target that implements the interface.

Protocol is generated by script cmd/generate.sh, which fetches latest version of protocol and creates types and domains (accessibility, animation, page, dom...) packages. Script can be run by calling

go generate

To start using package, create a new connection to chrome

// connects to chrome at 127.0.0.1:9222
conn, connErr := cri.NewConnection()

Connection instance can now be used to send commands to chrome

// get Page instance
pi := page.New(conn)
// send Page.enable command
pi.Enable()
// send Page.navigate command with url parameter
pi.Navigate(&page.NavigateRequest{Url: "https://www.example.com"})

To get started with devtools read https://developers.google.com/web/updates/2017/04/headless-chrome

Example

Example shows steps to take screenshot of a page.

package main

import (
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"

	"github.com/SKatiyar/cri"
	"github.com/SKatiyar/cri/emulation"
	"github.com/SKatiyar/cri/page"
)

func main() {
	conn, connErr := cri.NewConnection()
	if connErr != nil {
		panic(connErr)
	}

	pi := page.New(conn)
	ei := emulation.New(conn)

	if enableErr := pi.Enable(); enableErr != nil {
		panic(enableErr)
	}
	if overideErr := ei.SetDeviceMetricsOverride(&emulation.SetDeviceMetricsOverrideRequest{
		Width:  1280,
		Height: 800,
	}); overideErr != nil {
		panic(overideErr)
	}

	urls := []string{
		"https://www.google.com",
		"https://www.chromestatus.com",
		"https://www.facebook.com",
		"https://www.example.com",
	}

	for i := 0; i < len(urls); i++ {
		doneChn := make(chan struct{})
		pi.LoadEventFired(func(params *page.LoadEventFiredParams, err error) bool {
			close(doneChn)
			return false
		})

		_, navErr := pi.Navigate(&page.NavigateRequest{
			Url: urls[i],
		})
		if navErr != nil {
			panic(navErr)
		}

		<-doneChn

		pic, picErr := pi.CaptureScreenshot(nil)
		if picErr != nil {
			panic(picErr)
		}

		img, imgErr := base64.StdEncoding.DecodeString(pic.Data)
		if imgErr != nil {
			panic(imgErr)
		}

		fileName := strconv.Itoa(i) + ".png"
		if writeErr := ioutil.WriteFile(fileName, img, 0700); writeErr != nil {
			panic(writeErr)
		}

		fmt.Println(fileName)

		if removeErr := os.Remove(fileName); removeErr != nil {
			panic(removeErr)
		}
	}

}
Output:

0.png
1.png
2.png
3.png

Index

Examples

Constants

View Source
const DefaultAddress = "127.0.0.1:9222"

DefaultAddress for remote debugging protocol

View Source
const DefaultCommandTimeout = 10 * time.Second

DefaultCommandTimeout specifies default duration to receive command response

View Source
const DefaultEventTimeout = 10 * time.Second

DefaultEventTimeout specifies default duration to receive an event

Variables

This section is empty.

Functions

func BrowserProtocolVersion

func BrowserProtocolVersion() (major, minor string)

BrowserProtocolVersion returns current major and minor version of browser protocol.

func JsProtocolVersion

func JsProtocolVersion() (major, minor string)

JsProtocolVersion returns current major and minor version of js protocol.

Types

type Connection

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

Connection contains socket connection to remote target. Its safe to share same instance among multiple goroutines.

func NewConnection

func NewConnection(opts ...ConnectionOption) (*Connection, error)

NewConnection creates a connection to remote target. Connection options can be given in arguments using SetAddress, SetTargetID, SetSocketAddress etc. To see all options check ConnectionOptions.

When no arguments are provided, connection is created using DefaultAddress. If TargetID is provided, connection looks for remote target and connects to it. If SocketAddress is provided then Address and TargetID are ignored.

Example
package main

import (
	"crypto/tls"

	"github.com/SKatiyar/cri"
)

func main() {
	// create connection with default options
	cri.NewConnection()

	// override the remote address
	cri.NewConnection(cri.SetAddress("192.168.0.7:1290"))

	// select a target with ssl connection
	config := &tls.Config{ /* ...params */ }
	cri.NewConnection(cri.SetTargetID("<target-id>"), cri.SetTLSConfig(config))
}

func (*Connection) Close

func (c *Connection) Close() error

Close stops websocket connection.

func (*Connection) On

func (c *Connection) On(event string, closeChn chan struct{}) func(params interface{}) error

On listens for subscribed event. It takes event name and a non nil channel as arguments. It returns a function, which blocks current routine till channel is closed. When event is received, parameters are decoded in params argument or error is returned.

Example
package main

import (
	"github.com/SKatiyar/cri"
	"github.com/SKatiyar/cri/page"
)

func main() {
	// create new connection
	conn, _ := cri.NewConnection()

	// listen for page load
	// create close channel
	closeChn := make(chan struct{})
	// start listening
	decoder := conn.On(page.LoadEventFired, closeChn)
	for {
		var params page.LoadEventFiredParams
		if readErr := decoder(&params); readErr != nil {
			// if error occurs, signal close.
			close(closeChn)
			break
		}
	}
}

func (*Connection) Send

func (c *Connection) Send(command string, request, response interface{}) error

Send writes command and associated parameters to underlying connection. It waits for command response and decodes it in response argument. Timeout error is returned if response is not received.

Example
package main

import (
	"github.com/SKatiyar/cri"
	"github.com/SKatiyar/cri/browser"
	"github.com/SKatiyar/cri/emulation"
	"github.com/SKatiyar/cri/page"
)

func main() {
	// create new connection
	conn, _ := cri.NewConnection()

	// send Page.enable command
	conn.Send(page.Enable, nil, nil)

	// send Emulation.setDeviceMetricsOverride command with parameters
	conn.Send(emulation.SetDeviceMetricsOverride, emulation.SetDeviceMetricsOverrideRequest{}, nil)

	// send Browser.getVersion command and decode response
	var data browser.GetVersionResponse
	conn.Send(browser.GetVersion, nil, &data)
}

type ConnectionOption

type ConnectionOption func(*ConnectionOptions)

ConnectionOption defines a function type to set values of ConnectionOptions

func SetAddress

func SetAddress(addr string) ConnectionOption

SetAddress sets remote address for connection

func SetCommandTimeout

func SetCommandTimeout(timeout time.Duration) ConnectionOption

SetCommandTimeout sets commandTimeout for connection

func SetEventTimeout

func SetEventTimeout(timeout time.Duration) ConnectionOption

SetEventTimeout sets eventTimeout for connection

func SetLogger

func SetLogger(logger *log.Logger) ConnectionOption

SetLogger sets logging for connection

func SetSocketAddress

func SetSocketAddress(addr string) ConnectionOption

SetSocketAddress sets target websocket connection address

func SetTLSConfig

func SetTLSConfig(config *tls.Config) ConnectionOption

SetTLSConfig sets tls config for connection

func SetTargetID

func SetTargetID(targetID string) ConnectionOption

SetTargetID sets target for connection

type ConnectionOptions

type ConnectionOptions struct {
	// Address of remote devtools instance, default used is DefaultAddress
	Address string
	// TargetID of target to connect
	TargetID string
	// SocketAddress of target to connect
	SocketAddress string
	// TLSClientConfig specifies TLS configuration to use
	TLSConfig *tls.Config
	// EventTimeout specifies duration to receive an event, default used is DefaultEventTimeout
	EventTimeout time.Duration
	// CommandTimeout specifies duration to receive command response, default used is DefaultCommandTimeout
	CommandTimeout time.Duration
	// Logger if provided is used to print errors from connection reader.
	Logger *log.Logger
}

ConnectionOptions defines connection parameters

type Connector

type Connector interface {
	// Send sends a command with suplied request params to underlying
	// connection. It decodes result to response if provided.
	// Implementation should wait for response or timeout.
	Send(command string, request, response interface{}) error

	// On listens for an event. It takes event name and channel to signal close
	// as arguments. It returns a decoder function, which blocks till event is received.
	// Params received are decoded in params argument, returning an error if it fails.
	On(event string, closeChn chan struct{}) func(params interface{}) error
}

Connector interface defines methods required by command packages.

type Targets

type Targets []struct {
	Description          string `json:"description"`
	DevtoolsFrontendURL  string `json:"devtoolsFrontendUrl"`
	ID                   string `json:"id"`
	Title                string `json:"title"`
	Type                 string `json:"type"`
	URL                  string `json:"url"`
	WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
}

Targets represent a list of connectable remotes

func GetTargets

func GetTargets(opts ...ConnectionOption) (Targets, error)

GetTargets retreives targets in remote connection

type VersionResponse

type VersionResponse 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"`
	WebSocketDebuggerURL string `json:"webSocketDebuggerUrl"`
}

VersionResponse contains fields received in response to version query.

func GetVersion

func GetVersion(opts ...ConnectionOption) (VersionResponse, error)

GetVersion fetches the protocol version of remote

Directories

Path Synopsis
Package accessibility provides commands and events for Accessibility domain.
Package accessibility provides commands and events for Accessibility domain.
Package animation provides commands and events for Animation domain.
Package animation provides commands and events for Animation domain.
Package applicationcache provides commands and events for ApplicationCache domain.
Package applicationcache provides commands and events for ApplicationCache domain.
Package audits provides commands and events for Audits domain.
Package audits provides commands and events for Audits domain.
Package browser provides commands and events for Browser domain.
Package browser provides commands and events for Browser domain.
Package cachestorage provides commands and events for CacheStorage domain.
Package cachestorage provides commands and events for CacheStorage domain.
cmd
Package console provides commands and events for Console domain.
Package console provides commands and events for Console domain.
Package css provides commands and events for CSS domain.
Package css provides commands and events for CSS domain.
Package database provides commands and events for Database domain.
Package database provides commands and events for Database domain.
Package debugger provides commands and events for Debugger domain.
Package debugger provides commands and events for Debugger domain.
Package deviceorientation provides commands and events for DeviceOrientation domain.
Package deviceorientation provides commands and events for DeviceOrientation domain.
Package dom provides commands and events for DOM domain.
Package dom provides commands and events for DOM domain.
Package domdebugger provides commands and events for DOMDebugger domain.
Package domdebugger provides commands and events for DOMDebugger domain.
Package domsnapshot provides commands and events for DOMSnapshot domain.
Package domsnapshot provides commands and events for DOMSnapshot domain.
Package domstorage provides commands and events for DOMStorage domain.
Package domstorage provides commands and events for DOMStorage domain.
Package emulation provides commands and events for Emulation domain.
Package emulation provides commands and events for Emulation domain.
Package headlessexperimental provides commands and events for HeadlessExperimental domain.
Package headlessexperimental provides commands and events for HeadlessExperimental domain.
Package heapprofiler provides commands and events for HeapProfiler domain.
Package heapprofiler provides commands and events for HeapProfiler domain.
Package indexeddb provides commands and events for IndexedDB domain.
Package indexeddb provides commands and events for IndexedDB domain.
Package input provides commands and events for Input domain.
Package input provides commands and events for Input domain.
Package inspector provides commands and events for Inspector domain.
Package inspector provides commands and events for Inspector domain.
Package io provides commands and events for IO domain.
Package io provides commands and events for IO domain.
Package layertree provides commands and events for LayerTree domain.
Package layertree provides commands and events for LayerTree domain.
Package log provides commands and events for Log domain.
Package log provides commands and events for Log domain.
Package memory provides commands and events for Memory domain.
Package memory provides commands and events for Memory domain.
Package network provides commands and events for Network domain.
Package network provides commands and events for Network domain.
Package overlay provides commands and events for Overlay domain.
Package overlay provides commands and events for Overlay domain.
Package page provides commands and events for Page domain.
Package page provides commands and events for Page domain.
Package performance provides commands and events for Performance domain.
Package performance provides commands and events for Performance domain.
Package profiler provides commands and events for Profiler domain.
Package profiler provides commands and events for Profiler domain.
Package runtime provides commands and events for Runtime domain.
Package runtime provides commands and events for Runtime domain.
Package schema provides commands and events for Schema domain.
Package schema provides commands and events for Schema domain.
Package security provides commands and events for Security domain.
Package security provides commands and events for Security domain.
Package serviceworker provides commands and events for ServiceWorker domain.
Package serviceworker provides commands and events for ServiceWorker domain.
Package storage provides commands and events for Storage domain.
Package storage provides commands and events for Storage domain.
Package systeminfo provides commands and events for SystemInfo domain.
Package systeminfo provides commands and events for SystemInfo domain.
Package target provides commands and events for Target domain.
Package target provides commands and events for Target domain.
Package tethering provides commands and events for Tethering domain.
Package tethering provides commands and events for Tethering domain.
Package tracing provides commands and events for Tracing domain.
Package tracing provides commands and events for Tracing domain.

Jump to

Keyboard shortcuts

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