core

package
v1.10.0 Latest Latest
Warning

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

Go to latest
Published: Aug 24, 2023 License: MIT Imports: 18 Imported by: 1

Documentation

Overview

Commonly used commands for basic browser interaction.

Index

Constants

View Source
const (
	Portrait           Orientation = `portraitPrimary`
	Landscape                      = `landscapePrimary`
	PortraitSecondary              = `portraitSecondary`
	LandscapeSecondary             = `landscapeSecondary`
)

Variables

View Source
var RandomReferrerPrefix = `https://github.com/PerformLine/go-webfriend`
View Source
var WaitForLoadEventName string = `Page.loadEventFired`

Functions

This section is empty.

Types

type ClickArgs

type ClickArgs struct {
	// Permit multiple elements to be clicked.
	Multiple bool `json:"value"`

	// If Multiple clicks are permitted, what is the delay between each click.
	Delay time.Duration `json:"delay" default:"20ms"`
}

type ClickAtArgs

type ClickAtArgs struct {
	// The X-coordinate to click at
	X int `json:"x"`

	// The Y-coordinate to click at
	Y int `json:"y"`
}

type Commands

type Commands struct {
	*core.Commands
	// contains filtered or unexported fields
}

func New

func New(browser *browser.Browser, env utils.Runtime) *Commands

func (*Commands) Back

func (self *Commands) Back() error

Navigate back through the current tab's history.

func (*Commands) Click

func (self *Commands) Click(selector dom.Selector, args *ClickArgs) ([]*dom.Element, error)

Click on HTML element(s) matches by selector. If multiple is true, then all elements matched by selector will be clicked in the order they are returned. Otherwise, an error is returned unless selector matches exactly one element.

#### Examples

##### Click on the element with id "login" ``` click "#login" ```

##### Click on all `<a>` elements on the page, waiting 150ms between each click. ```

click "a" {
  multiple: true,
  delay:    "150ms",
}

```

func (*Commands) ClickAt

func (self *Commands) ClickAt(args *ClickAtArgs) ([]dom.Element, error)

Click the page at the given X, Y coordinates.

func (*Commands) CloseTab

func (self *Commands) CloseTab(id browser.TabID) error

[SKIP] Close the tab identified by the given ID.

func (*Commands) Configure

func (self *Commands) Configure(args *ConfigureArgs) error

Configures various features of the Remote Debugging protocol and provides environment setup.

func (*Commands) Exit

func (self *Commands) Exit() error

Immediately close the browser without error or delay.

func (*Commands) Export

func (self *Commands) Export(name string) error

Specify a variable that should be exported to external Javascripts.

func (*Commands) Field

func (self *Commands) Field(selector dom.Selector, args *FieldArgs) ([]*dom.Element, error)

Locate and enter data into a form input field.

#### Examples

##### Type in a username and password, then hit Enter to submit. ```

field '#username' {
  value: 'myuser',
}
field '#password' {
  value: 'p@ssw0rd!',
  enter: true,
}

```

func (*Commands) Focus

func (self *Commands) Focus(selector dom.Selector) (*dom.Element, error)

Focuses the given HTML element described by selector. One and only one element may match the selector.

func (*Commands) Go

func (self *Commands) Go(uri string, args *GoArgs) (*GoResponse, error)

Navigate to a URL.

#### Examples

##### Go to Google. ``` go "google.com" ```

##### Go to www.example.com, only wait for the first network response, and don't fail if the request times out. ```

go "https://www.exmaple.com" {
  timeout:             '10s',
  continue_on_timeout: true,
  load_event_name:     'Network.responseReceived',
}

```

func (*Commands) Highlight

func (self *Commands) Highlight(selector interface{}, args *HighlightArgs) error

Highlight the node matching the given selector, or clear all highlights if the selector is "none"

func (*Commands) Inspect

func (self *Commands) Inspect(args *InspectArgs) (*dom.Element, error)

Retrieve the element at the given coordinates, optionally highlighting it.

func (*Commands) Javascript

func (self *Commands) Javascript(script string) (interface{}, error)

Inject Javascript into the current page, evaluate it, and return the results. The script is wrapped in an anonymous function whose return value will be returned from this command as a native data type.

Scripts will have access to all exported variables in the calling script (exported with the "export" command). They are available to injected script as a plain object accessible using the "webfriend" variable.

#### Examples

##### Use the `webfriend` local variable to access Friendscript data from JavaScript, make a change, then pass it back. ``` $pi = 3.0

javascript "return webfriend.pi + 0.14" -> $pi # $pi is now 3.14 ```

##### Inject a script that will retrieve all `<a>` tags on a page and return their "href" attributes (if present). ``` javascript begin

var as = document.querySelectorAll('a');
var hrefs = [];

for(var i = 0; i < as.length; i++) {
    var a = as[i];
    var href = a.getAttribute('href');

    if (href && href.length) {
        hrefs.push(href);
    }
}

return hrefs;

end -> $result

# $result now contains an array of zero or more strings as returned from JavaScript. ```

func (*Commands) Key

func (self *Commands) Key(domKeyName string, args *KeyArgs) error

func (*Commands) Mouse

func (self *Commands) Mouse(args *MouseArgs) error

func (*Commands) Netrc

func (self *Commands) Netrc(machine string, args *NetrcArgs) (*NetrcResponse, error)

Retrieve a username and password from a .netrc-formatted file.

func (*Commands) NewTab

func (self *Commands) NewTab(url string, args *NewTabArgs) (browser.TabID, error)

[SKIP] Open a new tab and navigate to the given URL.

func (*Commands) Reload

func (self *Commands) Reload() error

Reload the currently active tab.

func (*Commands) Resize

func (self *Commands) Resize(args *ResizeArgs) (*ResizeResponse, error)

Resizes the active viewport of the current page using the Chrome Device Emulation API. This does not resize the window itself, but rather the area the current page interprets the window to be.

This is useful for setting the size of the area that will be rendered for screenshots and screencasts, or for testing responsive design elements.

func (*Commands) Rpc

func (self *Commands) Rpc(method string, args map[string]interface{}) (interface{}, error)

[SKIP] Directly call an RPC method with the given parameters.

func (*Commands) ScrollTo

func (self *Commands) ScrollTo(selector dom.Selector) error

Scroll the viewport to the location of the first element matched by selector.

func (*Commands) ScrollToCoords

func (self *Commands) ScrollToCoords(x int, y int) error

Scroll the viewport to the given X,Y coordinates relative to the top-left of the current page.

func (*Commands) Select

func (self *Commands) Select(selector dom.Selector, args *SelectArgs) ([]*dom.Element, error)

Polls the DOM for an element that matches the given selector. Either the element will be found and returned within the given timeout, or a TimeoutError will be returned.

func (*Commands) Stop

func (self *Commands) Stop() error

Stop loading the currently active tab.

func (*Commands) SwitchRoot

func (self *Commands) SwitchRoot(selector dom.Selector) error

[SKIP] Change the current selector scope to be rooted at the given element. If selector is empty, the scope is set to the document element (i.e.: global).

func (*Commands) SwitchTab

func (self *Commands) SwitchTab(id browser.TabID) (*browser.Tab, error)

[SKIP] Switches the active tab to a given tab.

func (*Commands) Tabs

func (self *Commands) Tabs() ([]browser.Tab, error)

[SKIP] Return all currently open tabs.

func (*Commands) Type

func (self *Commands) Type(input interface{}, args *TypeArgs) (string, error)

Input the given textual data as keyboard input into the currently focused page element.

func (*Commands) Unexport

func (self *Commands) Unexport(name string) error

Specify a variable that should be unexported.

func (*Commands) WaitFor

func (self *Commands) WaitFor(event string, args *WaitForArgs) error

Wait for a specific event or events matching the given glob pattern, up to an optional Timeout duration.

func (*Commands) WaitForLoad

func (self *Commands) WaitForLoad(args *WaitForArgs) error

Wait for a page load event.

type ConfigureArgs

type ConfigureArgs struct {
	// Override the default User-Agent header sent with all requests
	UserAgent string `json:"user_agent"`

	// Specify the Geographic latitude to emulate [-90.0, 90.0]
	Latitude float64 `json:"latitude"`

	// Specify the Geographic longitude to emulate [-180.0, 180.0]
	Longitude float64 `json:"longitude"`

	// Specify a Geolocation error margin (accurate to within n meters)
	Accuracy float64 `json:"accuracy" default:"1"`

	// Disable JavaScript execution in the browser.
	DisableScripts bool `json:"disable_scripts"`

	// Emulate a touch-capable device.
	EmulateTouch bool `json:"emulate_touch"`

	// Set the default background color of the underlying window in the following formats: `#RRGGBB`, `#RRGGBBAA`, `rgb()`, `rgba()`, `hsv()`, `hsva()`, `hsl()`, `hsla()`.
	BackgroundColor string `json:"background_color"`

	// Set whether scrollbars should be hidden all the time.
	HideScrollbars bool `json:"hide_scrollbars"`
}

type FieldArgs

type FieldArgs struct {
	// The value to enter into the field.
	Value interface{} `json:"value"`

	// Whether to clear the existing contents of the field before entering new data.
	Autoclear bool `json:"autoclear" default:"true"`

	// Whether to automatically send an "Enter" keystroke after typing in the given value
	Enter bool `json:"enter"`

	// An element to click after the field value is changed.
	Click dom.Selector `json:"click"`
}

type GoArgs

type GoArgs struct {
	// If a URL is specified, it will be used as the HTTP Referer [sic] header
	// field when going to the given page. If the URL of the currently-loaded
	// page and the referrer are the same, the page will no change.
	//
	// For this reason, you may specify the special value 'random', which will
	// generate a URL with a randomly generated path component to ensure that
	// it is always different from the current page. Specifying None will omit
	// the field from the request.
	Referrer string `json:"referrer"`

	// Whether to block until the page has finished loading.
	WaitForLoad bool `json:"wait_for_load" default:"true"`

	// The amount of time to wait for the page to load.
	Timeout time.Duration `json:"timeout" default:"30s"`

	// The amount of time to poll for the originating network request.
	RequestPollTimeout time.Duration `json:"request_poll_timeout" default:"5s"`

	// Whether the resources stack that is queried in page::resources and
	// page::resource is cleared before navigating. Set this to false to
	// preserve the ability to retrieve data that was loaded on previous pages.
	ClearRequests bool `json:"clear_requests" default:"false"`

	// Whether the originating network request is required in the return value.  If this is
	// false, the response may be missing status, headers, and timing details.
	RequireOriginatingRequest bool `json:"require_originating_request" default:"true"`

	// Whether to continue execution if an error is encountered during page
	// load (e.g.: HTTP 4xx/5xx, SSL, TCP connection errors).
	ContinueOnError bool `json:"continue_on_error"`

	// These HTTP status codes are not considered errors.
	ContinueStatuses []int `json:"continue_statuses"`

	// Whether to continue execution if load_event_name is not seen before
	// timeout elapses.
	ContinueOnTimeout bool `json:"continue_on_timeout" default:"false"`

	// The RPC event to wait for before proceeding to the next command.
	LoadEventName string `json:"load_event_name" default:"Page.loadEventFired"`

	// Provide a username if one is requested via HTTP Basic authentication.
	Username string `json:"username"`

	// Provide a password if one is requested via HTTP Basic authentication.
	Password string `json:"password"`

	// Only provide credentials if the HTTP Basic Authentication Realm matches this one.
	Realm string `json:"realm"`
}

type GoResponse

type GoResponse struct {
	// The final URL of the page that was loaded.
	URL string `json:"url"`

	// The HTTP status code of the loaded page.
	Status int `json:"status"`

	// A map of durations (in milliseconds) that various phases of the page load took.
	TimingDetails map[string]float64 `json:"timing"`

	// Map of HTTP response headers.
	Headers map[string]string `json:"headers"`

	// The MIME type of the response content.
	MimeType string `json:"mimetype"`

	// The remote address of the loaded page.
	RemoteAddress string `json:"remoteAddress"`

	// The protocol that was negotiated and used to load the page.
	Protocol string `json:"protocol"`
}

type HighlightArgs

type HighlightArgs struct {
	// The red component of the highlight color (0 <= r < 256)
	R int `json:"r" default:"0"`

	// The green component of the highlight color (0 <= g < 256)
	G int `json:"g" default:"128"`

	// The blue component of the highlight color (0 <= b < 256)
	B int `json:"b" default:"128"`

	// The alpha component of the highlight color (0.0 <= a <= 1.0)
	A float64 `json:"a" default:"0.5"`
}

type InspectArgs

type InspectArgs struct {
	// The X-coordinate to inspect.
	X float64 `json:"x"`

	// The Y-coordinate to inspect.
	Y float64 `json:"y"`

	// Whether to highlight the inspected DOM element or not.
	Highlight bool `json:"highlight" default:"true"`

	// The red component of the highlight color (0 <= r < 256)
	R int `json:"r" default:"0"`

	// The green component of the highlight color (0 <= g < 256)
	G int `json:"g" default:"128"`

	// The blue component of the highlight color (0 <= b < 256)
	B int `json:"b" default:"128"`

	// The alpha component of the highlight color (0.0 <= a <= 1.0)
	A float64 `json:"a" default:"0.5"`
}

type KeyArgs

type KeyArgs struct {
	// The keyboard action to take; either "press" or "release"
	Action  string `json:"action" default:"press"`
	Alt     bool   `json:"alt,omitempty"`
	Control bool   `json:"control,omitempty"`
	Meta    bool   `json:"meta,omitempty"`
	Shift   bool   `json:"shift,omitempty"`

	// The numeric decimal keycode to send.
	KeyCode int `json:"keycode,omitempty"`
}

type MouseArgs

type MouseArgs struct {
	// The X-coordinate to perform the mouse action at.
	X float64 `json:"x"`

	// The Y-coordinate to perform the mouse action at.
	Y float64 `json:"y"`

	// The action that should be performed; one of "move", "press", "release", or "scroll".
	Action string `json:"action" default:"move"`

	// Which mouse button to depress when performing the action; one of "left", "middle", or "right".
	Button string `json:"button,omitempty"`

	// Whether the Alt-key should be held down when emitting the event.
	Alt bool `json:"alt,omitempty"`

	// Whether the Control-key should be held down when emitting the event.
	Control bool `json:"control,omitempty"`

	// Whether the Meta/Command-key should be held down when emitting the event.
	Meta bool `json:"meta,omitempty"`

	// Whether the Shift-key should be held down when emitting the event.
	Shift bool `json:"shift,omitempty"`

	// For "scroll" actions, this indicates how much to scroll horizontally (positive for right, negative for left).
	WheelX float64 `json:"wheelX,omitempty"`

	// For "scroll" actions, this indicates how much to scroll vertically (positive for up, negative for down)
	WheelY float64 `json:"wheelY,omitempty"`

	// How many clicks to issue if action is "press"
	Count int `json:"count,omitempty"`
}

type NetrcArgs

type NetrcArgs struct {
	// The path to the .netrc file to load values from.
	Filename string `json:"filename" default:"~/.netrc"`

	// A list of additional, non-standard fields to retrieve from the .netrc entry
	ExtraFields []string `json:"extra_fields"`
}

type NetrcResponse

type NetrcResponse struct {
	// Whether there was a match or not.
	OK bool `json:"ok"`

	// The machine name that matched.
	Machine string `json:"machine"`

	// The login name.
	Login string `json:"login"`

	// The password.
	Password string `json:"password"`

	// Any additional values retrieved from the entry
	Fields map[string]string
}

type NewTabArgs

type NewTabArgs struct {
	// The width and height (in pixels) that the tab should be created with.
	Width int `json:"width"`

	// The height and height (in pixels) that the tab should be created with.
	Height int `json:"height"`

	// Whether to automatically switch to the newly-created tab as the active
	// tab for subsequent commands.
	Autoswitch bool `json:"autoswitch" default:"true"`
}

type Orientation

type Orientation string

type ResizeArgs

type ResizeArgs struct {
	// The width of the screen.
	Width int `json:"width"`

	// The height of the screen.
	Height int `json:"height"`

	// The scaling factor of the content.
	Scale float64 `json:"scale"`

	// Whether to emulate a mobile device or not. If a map is provided, mobile
	// emulation will be enabled and configured using the following keys:
	//
	// <br>
	//
	// Value    | Data Type     | Description
	// ---------|---------------|-------------
	// *width*  | int, optional | The width of the mobile screen to emulate.
	// *height* | int, optional | The height of the mobile screen to emulate.
	// *x*      | int, optional | The horizontal position of the currently viewable portion of the mobile screen.
	// *y*      | int, optional | The vertical position of the currently viewable portion of the mobile screen.
	//
	Mobile interface{} `json:"mobile"`

	// Whether to fit the viewport contents to the available area or not.
	FitWindow bool `json:"fit_window"`

	// Which screen orientation to emulate, if any.
	Orientation string `json:"orientation" default:"landscapePrimary"`

	// The angle of the screen to emulate (in degrees; 0-360).
	Angle int `json:"angle"`
}

type ResizeResponse

type ResizeResponse struct {
	// The final width of the page after resize.
	Width int `json:"width"`

	// The final height of the page after resize.
	Height int `json:"height"`
}

type SelectArgs

type SelectArgs struct {
	// The timeout before we stop waiting for the element to appear.
	Timeout time.Duration `json:"timeout" default:"5s"`

	// The minimum number of matches necessary to be considered a successful match.
	MinMatches int `json:"min_matches" default:"1"`

	// The polling interval between element re-checks.
	Interval time.Duration `json:"interval" default:"125ms"`
}

type TypeArgs

type TypeArgs struct {
	Alt     bool `json:"alt"`
	Control bool `json:"control"`
	Shift   bool `json:"shift"`
	Meta    bool `json:"meta"`

	// Whether the text being input is issued via the numeric keypad or not.
	IsKeypad bool `json:"is_keypad"`

	// How long that each individual keystroke will remain down for.
	KeyDownTime time.Duration `json:"key_down_time" default:"30ms"`

	// An amount of time to randomly vary the `key_down_time` duration from within each keystroke.
	KeyDownJitter time.Duration `json:"key_down_jitter"`

	// How long to wait between issuing individual keystrokes.
	Delay time.Duration `json:"delay" default:"30ms"`

	// An amount of time to randomly vary the delay duration from between keystrokes.
	DelayJitter time.Duration `json:"delay_jitter"`
}

type WaitForArgs

type WaitForArgs struct {
	// The timeout before we stop waiting for the event.
	Timeout time.Duration `json:"timeout" default:"30s"`
}

Jump to

Keyboard shortcuts

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