common

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Apr 26, 2024 License: AGPL-3.0 Imports: 62 Imported by: 0

Documentation

Overview

Package common provides the main logic of the browser module. This package will be split into multiple packages in the future.

Index

Constants

View Source
const (
	BrowserStateOpen int64 = iota
	BrowserStateClosed
)
View Source
const (
	DefaultLocale       string        = "en-US"
	DefaultScreenWidth  int64         = 1280
	DefaultScreenHeight int64         = 720
	DefaultTimeout      time.Duration = 30 * time.Second

	LifeCycleNetworkIdleTimeout time.Duration = 500 * time.Millisecond

	StrictModeOff = false
)
View Source
const (
	EventBrowserDisconnected string = "disconnected"

	EventBrowserContextPage string = "page"

	EventConnectionClose string = "close"

	EventFrameNavigation   string = "navigation"
	EventFrameAddLifecycle string = "addlifecycle"

	EventPageClose           string = "close"
	EventPageConsole         string = "console"
	EventPageCrash           string = "crash"
	EventPageDialog          string = "dialog"
	EventPageDownload        string = "download"
	EventPageFilechooser     string = "filechooser"
	EventPageFrameAttached   string = "frameattached"
	EventPageFrameDetached   string = "framedetached"
	EventPageFrameNavigated  string = "framenavigated"
	EventPageError           string = "pageerror"
	EventPagePopup           string = "popup"
	EventPageRequest         string = "request"
	EventPageRequestFailed   string = "requestfailed"
	EventPageRequestFinished string = "requestfinished"
	EventPageResponse        string = "response"
	EventPageWebSocket       string = "websocket"
	EventPageWorker          string = "worker"

	EventSessionClosed string = "close"

	EventWorkerClose string = "close"
)
View Source
const (
	ModifierKeyAlt int64 = 1 << iota
	ModifierKeyControl
	ModifierKeyMeta
	ModifierKeyShift
)
View Source
const BlankPage = "about:blank"

BlankPage represents a blank page.

Variables

This section is empty.

Functions

func GetDevices

func GetDevices() map[string]Device

GetDevices returns predefined emulation settings for many end-user devices.

func GetIterationID added in v0.6.0

func GetIterationID(ctx context.Context) string

GetIterationID returns the iteration identifier attached to the context.

func GetNetworkProfiles added in v1.2.0

func GetNetworkProfiles() map[string]NetworkProfile

GetNetworkProfiles returns NetworkProfiles which are ready to be used to throttle the network with page.throttleNetwork.

func NewJSHandle

func NewJSHandle(
	ctx context.Context,
	s session,
	ectx *ExecutionContext,
	f *Frame,
	ro *runtime.RemoteObject,
	l *log.Logger,
) jsHandle

NewJSHandle creates a new JS handle referencing a remote object.

func TraceAPICall added in v1.3.0

func TraceAPICall(
	ctx context.Context, targetID string, spanName string, opts ...trace.SpanStartOption,
) (context.Context, trace.Span)

TraceAPICall is a helper method that retrieves the Tracer from the given ctx and calls its TraceAPICall implementation. If the Tracer is not present in the given ctx, it returns a noopSpan and the given context.

func TraceEvent added in v1.3.0

func TraceEvent(
	ctx context.Context, targetID string, eventName string, spanID string, options ...trace.SpanStartOption,
) (context.Context, trace.Span)

TraceEvent is a helper method that retrieves the Tracer from the given ctx and calls its TraceEvent implementation. If the Tracer is not present in the given ctx, it returns a noopSpan and the given context.

func TraceNavigation added in v1.3.0

func TraceNavigation(
	ctx context.Context, targetID string, opts ...trace.SpanStartOption,
) (context.Context, trace.Span)

TraceNavigation is a helper method that retrieves the Tracer from the given ctx and calls its TraceNavigation implementation. If the Tracer is not present in the given ctx, it returns a noopSpan and the given context.

func TrimQuotes added in v0.2.0

func TrimQuotes(s string) string

TrimQuotes removes surrounding single or double quotes from s. We're not using strings.Trim() to avoid trimming unbalanced values, e.g. `"'arg` shouldn't change. Source: https://stackoverflow.com/a/48451906

func WithBrowserOptions added in v1.0.0

func WithBrowserOptions(ctx context.Context, opts *BrowserOptions) context.Context

WithBrowserOptions adds the browser options to the context.

func WithHooks

func WithHooks(ctx context.Context, hooks *Hooks) context.Context

func WithIterationID added in v0.6.0

func WithIterationID(ctx context.Context, iterID string) context.Context

WithIterationID adds an identifier for the current iteration to the context.

func WithTracer added in v1.3.0

func WithTracer(ctx context.Context, tracer Tracer) context.Context

WithTracer adds the given tracer to the context.

Types

type Action

type Action interface {
	Do(context.Context) error
}

Action is the general interface of an CDP action.

type ActionFunc

type ActionFunc func(context.Context) error

ActionFunc is an adapter to allow regular functions to be used as an Action.

func (ActionFunc) Do

func (f ActionFunc) Do(ctx context.Context) error

Do executes the func f using the provided context.

type Barrier

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

func NewBarrier

func NewBarrier() *Barrier

func (*Barrier) AddFrameNavigation

func (b *Barrier) AddFrameNavigation(frame *Frame)

func (*Barrier) Wait

func (b *Barrier) Wait(ctx context.Context) error

type BaseEventEmitter

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

BaseEventEmitter emits events to registered handlers.

func NewBaseEventEmitter

func NewBaseEventEmitter(ctx context.Context) BaseEventEmitter

NewBaseEventEmitter creates a new instance of a base event emitter.

type BaseJSHandle

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

BaseJSHandle represents a JS object in an execution context.

func (*BaseJSHandle) AsElement

func (h *BaseJSHandle) AsElement() *ElementHandle

AsElement returns an element handle if this JSHandle is a reference to a JS HTML element.

func (*BaseJSHandle) Dispose

func (h *BaseJSHandle) Dispose()

Dispose releases the remote object.

func (*BaseJSHandle) Evaluate

func (h *BaseJSHandle) Evaluate(pageFunc string, args ...any) any

Evaluate will evaluate provided page function within an execution context.

func (*BaseJSHandle) EvaluateHandle

func (h *BaseJSHandle) EvaluateHandle(pageFunc string, args ...any) (JSHandleAPI, error)

EvaluateHandle will evaluate provided page function within an execution context.

func (*BaseJSHandle) GetProperties

func (h *BaseJSHandle) GetProperties() (map[string]JSHandleAPI, error)

GetProperties retreives the JS handle's properties.

func (*BaseJSHandle) JSONValue

func (h *BaseJSHandle) JSONValue() (string, error)

JSONValue returns a JSON version of this JS handle.

func (*BaseJSHandle) ObjectID added in v0.3.0

func (h *BaseJSHandle) ObjectID() runtime.RemoteObjectID

ObjectID returns the remote object ID.

type BigIntParseError

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

func (BigIntParseError) Error

func (e BigIntParseError) Error() string

Error satisfies the builtin error interface.

func (BigIntParseError) Is

func (e BigIntParseError) Is(target error) bool

Is satisfies the builtin error Is interface.

func (BigIntParseError) Unwrap

func (e BigIntParseError) Unwrap() error

Unwrap satisfies the builtin error Unwrap interface.

type Browser

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

Browser stores a Browser context.

func NewBrowser

func NewBrowser(
	ctx context.Context,
	cancel context.CancelFunc,
	browserProc *BrowserProcess,
	browserOpts *BrowserOptions,
	logger *log.Logger,
) (*Browser, error)

NewBrowser creates a new browser, connects to it, then returns it.

func (*Browser) Close

func (b *Browser) Close()

Close shuts down the browser.

func (*Browser) CloseContext added in v1.2.0

func (b *Browser) CloseContext() error

CloseContext is a short-cut function to close the current browser's context. If there is no active browser context, it returns an error.

func (*Browser) Context added in v1.0.0

func (b *Browser) Context() *BrowserContext

Context returns the current browser context or nil.

func (*Browser) IsConnected

func (b *Browser) IsConnected() bool

IsConnected returns whether the WebSocket connection to the browser process is active or not.

func (*Browser) NewContext

func (b *Browser) NewContext(opts goja.Value) (*BrowserContext, error)

NewContext creates a new incognito-like browser context.

func (*Browser) NewPage

func (b *Browser) NewPage(opts goja.Value) (*Page, error)

NewPage creates a new tab in the browser window.

func (*Browser) On added in v0.3.0

func (b *Browser) On(event string) (bool, error)

On returns a Promise that is resolved when the browser process is disconnected. The only accepted event value is "disconnected".

func (*Browser) UserAgent

func (b *Browser) UserAgent() string

UserAgent returns the controlled browser's user agent string.

func (*Browser) Version

func (b *Browser) Version() string

Version returns the controlled browser's version.

func (*Browser) WsURL added in v0.9.0

func (b *Browser) WsURL() string

WsURL returns the Websocket URL that the browser is listening on for CDP clients.

type BrowserContext

type BrowserContext struct {
	BaseEventEmitter
	// contains filtered or unexported fields
}

BrowserContext stores context information for a single independent browser session. A newly launched browser instance contains a default browser context. Any browser context created aside from the default will be considered an "incognito" browser context and will not store any data on disk.

func NewBrowserContext

func NewBrowserContext(
	ctx context.Context, browser *Browser, id cdp.BrowserContextID, opts *BrowserContextOptions, logger *log.Logger,
) (*BrowserContext, error)

NewBrowserContext creates a new browser context.

func (*BrowserContext) AddCookies

func (b *BrowserContext) AddCookies(cookies []*Cookie) error

AddCookies adds cookies into this browser context. All pages within this context will have these cookies installed.

func (*BrowserContext) AddInitScript

func (b *BrowserContext) AddInitScript(script string) error

AddInitScript adds a script that will be initialized on all new pages.

func (*BrowserContext) Browser

func (b *BrowserContext) Browser() *Browser

Browser returns the browser instance that this browser context belongs to.

func (*BrowserContext) ClearCookies

func (b *BrowserContext) ClearCookies() error

ClearCookies clears cookies.

func (*BrowserContext) ClearPermissions

func (b *BrowserContext) ClearPermissions() error

ClearPermissions clears any permission overrides.

func (*BrowserContext) Close

func (b *BrowserContext) Close()

Close shuts down the browser context.

func (*BrowserContext) Cookies

func (b *BrowserContext) Cookies(urls ...string) ([]*Cookie, error)

Cookies returns all cookies. Some of them can be added with the AddCookies method and some of them are automatically taken from the browser context when it is created. And some of them are set by the page, i.e., using the Set-Cookie HTTP header or via JavaScript like document.cookie.

func (*BrowserContext) GrantPermissions

func (b *BrowserContext) GrantPermissions(permissions []string, opts *GrantPermissionsOptions) error

GrantPermissions enables the specified permissions, all others will be disabled.

func (*BrowserContext) NewPage

func (b *BrowserContext) NewPage() (*Page, error)

NewPage creates a new page inside this browser context.

func (*BrowserContext) Pages

func (b *BrowserContext) Pages() []*Page

Pages returns a list of pages inside this browser context.

func (*BrowserContext) SetDefaultNavigationTimeout

func (b *BrowserContext) SetDefaultNavigationTimeout(timeout int64)

SetDefaultNavigationTimeout sets the default navigation timeout in milliseconds.

func (*BrowserContext) SetDefaultTimeout

func (b *BrowserContext) SetDefaultTimeout(timeout int64)

SetDefaultTimeout sets the default maximum timeout in milliseconds.

func (*BrowserContext) SetGeolocation

func (b *BrowserContext) SetGeolocation(geolocation goja.Value)

SetGeolocation overrides the geo location of the user.

func (*BrowserContext) SetHTTPCredentials deprecated

func (b *BrowserContext) SetHTTPCredentials(httpCredentials goja.Value)

SetHTTPCredentials sets username/password credentials to use for HTTP authentication.

Deprecated: Create a new BrowserContext with httpCredentials instead. See for details: - https://github.com/microsoft/playwright/issues/2196#issuecomment-627134837 - https://github.com/microsoft/playwright/pull/2763

func (*BrowserContext) SetOffline

func (b *BrowserContext) SetOffline(offline bool)

SetOffline toggles the browser's connectivity on/off.

func (*BrowserContext) Timeout added in v1.2.0

func (b *BrowserContext) Timeout() time.Duration

Timeout will return the default timeout or the one set by the user.

func (*BrowserContext) WaitForEvent

func (b *BrowserContext) WaitForEvent(event string, f func(p *Page) (bool, error), timeout time.Duration) (any, error)

WaitForEvent waits for event.

type BrowserContextOptions

type BrowserContextOptions struct {
	AcceptDownloads   bool              `js:"acceptDownloads"`
	BypassCSP         bool              `js:"bypassCSP"`
	ColorScheme       ColorScheme       `js:"colorScheme"`
	DeviceScaleFactor float64           `js:"deviceScaleFactor"`
	ExtraHTTPHeaders  map[string]string `js:"extraHTTPHeaders"`
	Geolocation       *Geolocation      `js:"geolocation"`
	HasTouch          bool              `js:"hasTouch"`
	HttpCredentials   *Credentials      `js:"httpCredentials"`
	IgnoreHTTPSErrors bool              `js:"ignoreHTTPSErrors"`
	IsMobile          bool              `js:"isMobile"`
	JavaScriptEnabled bool              `js:"javaScriptEnabled"`
	Locale            string            `js:"locale"`
	Offline           bool              `js:"offline"`
	Permissions       []string          `js:"permissions"`
	ReducedMotion     ReducedMotion     `js:"reducedMotion"`
	Screen            *Screen           `js:"screen"`
	TimezoneID        string            `js:"timezoneID"`
	UserAgent         string            `js:"userAgent"`
	VideosPath        string            `js:"videosPath"`
	Viewport          *Viewport         `js:"viewport"`
}

BrowserContextOptions stores browser context options.

func NewBrowserContextOptions

func NewBrowserContextOptions() *BrowserContextOptions

NewBrowserContextOptions creates a default set of browser context options.

func (*BrowserContextOptions) Parse

func (b *BrowserContextOptions) Parse(ctx context.Context, opts goja.Value) error

type BrowserOptions added in v1.0.0

type BrowserOptions struct {
	Args              []string
	Debug             bool
	ExecutablePath    string
	Headless          bool
	IgnoreDefaultArgs []string
	LogCategoryFilter string
	// TODO: Do not expose slowMo option by now.
	// See https://github.com/grafana/xk6-browser/issues/857.
	SlowMo  time.Duration
	Timeout time.Duration
	// contains filtered or unexported fields
}

BrowserOptions stores browser options.

func GetBrowserOptions added in v1.0.0

func GetBrowserOptions(ctx context.Context) *BrowserOptions

GetBrowserOptions returns the browser options attached to the context.

func NewLocalBrowserOptions added in v1.0.0

func NewLocalBrowserOptions() *BrowserOptions

NewLocalBrowserOptions returns a new BrowserOptions for a browser launched in the local machine.

func NewRemoteBrowserOptions added in v1.0.0

func NewRemoteBrowserOptions() *BrowserOptions

NewRemoteBrowserOptions returns a new BrowserOptions for a browser running in a remote machine.

func (*BrowserOptions) Parse added in v1.0.0

func (bo *BrowserOptions) Parse(
	ctx context.Context, logger *log.Logger, opts map[string]any, envLookup env.LookupFunc,
) error

Parse parses browser options from a JS object.

type BrowserProcess

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

func NewLocalBrowserProcess added in v0.9.0

func NewLocalBrowserProcess(
	ctx context.Context, path string, args []string, dataDir *storage.Dir,
	ctxCancel context.CancelFunc, logger *log.Logger,
) (*BrowserProcess, error)

NewLocalBrowserProcess starts a local browser process and returns a new BrowserProcess instance to interact with it.

func NewRemoteBrowserProcess added in v0.9.0

func NewRemoteBrowserProcess(
	ctx context.Context, wsURL string, ctxCancel context.CancelFunc, logger *log.Logger,
) (*BrowserProcess, error)

NewRemoteBrowserProcess returns a new BrowserProcess instance which references a remote browser process.

func (*BrowserProcess) Cleanup added in v0.9.0

func (p *BrowserProcess) Cleanup() error

Cleanup cleans up the metadata associated with the browser process, mainly the browser data directory.

func (*BrowserProcess) GracefulClose

func (p *BrowserProcess) GracefulClose()

GracefulClose triggers a graceful closing of the browser process.

func (*BrowserProcess) Pid added in v0.1.1

func (p *BrowserProcess) Pid() int

Pid returns the browser process ID, or -1 if this is unknown.

func (*BrowserProcess) Terminate

func (p *BrowserProcess) Terminate()

Terminate triggers the termination of the browser process.

func (*BrowserProcess) WsURL

func (p *BrowserProcess) WsURL() string

WsURL returns the Websocket URL that the browser is listening on for CDP clients.

type CPUProfile added in v1.2.0

type CPUProfile struct {
	// rate as a slowdown factor (1 is no throttle, 2 is 2x slowdown, etc).
	Rate float64
}

CPUProfile is used in throttleCPU.

type ColorScheme

type ColorScheme string

ColorScheme represents a browser color scheme.

const (
	ColorSchemeLight        ColorScheme = "light"
	ColorSchemeDark         ColorScheme = "dark"
	ColorSchemeNoPreference ColorScheme = "no-preference"
)

Valid color schemes.

func (ColorScheme) MarshalJSON

func (c ColorScheme) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted JSON string.

func (ColorScheme) String

func (c ColorScheme) String() string

func (*ColorScheme) UnmarshalJSON

func (c *ColorScheme) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a quoted JSON string to the enum value.

type Connection

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

Connection represents a WebSocket connection and the root "Browser Session".

                                          ┌───────────────────────────────────────────────────────────────────┐
                                          │                                                                   │
                                          │                          Browser Process                          │
                                          │                                                                   │
                                          └───────────────────────────────────────────────────────────────────┘
┌───────────────────────────┐                                           │      ▲
│Reads JSON-RPC CDP messages│                                           │      │
│from WS connection and puts│                                           ▼      │
│ them on incoming queue of │             ┌───────────────────────────────────────────────────────────────────┐
│    target session, as     ├─────────────■                                                                   │
│   identified by message   │             │                       WebSocket Connection                        │
│   session ID. Messages    │             │                                                                   │
│ without a session ID are  │             └───────────────────────────────────────────────────────────────────┘
│considered to belong to the│                    │      ▲                                       │      ▲
│  root "Browser Session".  │                    │      │                                       │      │
└───────────────────────────┘                    ▼      │                                       ▼      │
┌───────────────────────────┐             ┌────────────────────┐                         ┌────────────────────┐
│  Handles CDP messages on  ├─────────────■                    │                         │                    │
│incoming queue and puts CDP│             │      Session       │      *  *  *  *  *      │      Session       │
│   messages on outgoing    │             │                    │                         │                    │
│ channel of WS connection. │             └────────────────────┘                         └────────────────────┘
└───────────────────────────┘                    │      ▲                                       │      ▲
  │      │                                       │      │                                       │      │
  ▼      │                                       ▼      │                                       ▼      │

┌───────────────────────────┐             ┌────────────────────┐                         ┌────────────────────┐
│Registers with session as a├─────────────■                    │                         │                    │
│handler for a specific CDP │             │   Event Listener   │      *  *  *  *  *      │   Event Listener   │
│       Domain event.       │             │                    │                         │                    │
└───────────────────────────┘             └────────────────────┘                         └────────────────────┘

func NewConnection

func NewConnection(
	ctx context.Context,
	wsURL string,
	logger *log.Logger,
	onTargetAttachedToTarget func(*target.EventAttachedToTarget) bool,
) (*Connection, error)

NewConnection creates a new browser.

func (*Connection) Close

func (c *Connection) Close(args ...goja.Value)

Close cleanly closes the WebSocket connection. It returns an error if sending the Close control frame fails.

func (*Connection) Execute

func (c *Connection) Execute(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error

Execute implements cdproto.Executor and performs a synchronous send and receive.

func (*Connection) IgnoreIOErrors added in v0.6.0

func (c *Connection) IgnoreIOErrors()

IgnoreIOErrors signals that the connection will soon be closed, so that any received IO errors can be disregarded.

type ConsoleMessage added in v1.2.0

type ConsoleMessage struct {
	// Args represent the list of arguments passed to a console function call.
	Args []JSHandleAPI

	// Page is the page that produced the console message, if any.
	Page *Page

	// Text represents the text of the console message.
	Text string

	// Type is the type of the console message.
	// It can be one of 'log', 'debug', 'info', 'error', 'warning', 'dir', 'dirxml',
	// 'table', 'trace', 'clear', 'startGroup', 'startGroupCollapsed', 'endGroup',
	// 'assert', 'profile', 'profileEnd', 'count', 'timeEnd'.
	Type string
}

ConsoleMessage represents a page console message.

type Cookie struct {
	Name     string         `js:"name" json:"name"`         // Cookie name.
	Value    string         `js:"value" json:"value"`       // Cookie value.
	Domain   string         `js:"domain" json:"domain"`     // Cookie domain.
	Path     string         `js:"path" json:"path"`         // Cookie path.
	HTTPOnly bool           `js:"httpOnly" json:"httpOnly"` // True if cookie is http-only.
	Secure   bool           `js:"secure" json:"secure"`     // True if cookie is secure.
	SameSite CookieSameSite `js:"sameSite" json:"sameSite"` // Cookie SameSite type.
	URL      string         `js:"url" json:"url,omitempty"` // Cookie URL.
	// Cookie expiration date as the number of seconds since the UNIX epoch.
	Expires int64 `js:"expires" json:"expires"`
}

Cookie represents a browser cookie.

https://datatracker.ietf.org/doc/html/rfc6265.

type CookieSameSite added in v1.2.0

type CookieSameSite string

CookieSameSite represents the cookie's 'SameSite' status.

https://tools.ietf.org/html/draft-west-first-party-cookies.

const (
	// CookieSameSiteStrict sets the cookie to be sent only in a first-party
	// context and not be sent along with requests initiated by third party
	// websites.
	CookieSameSiteStrict CookieSameSite = "Strict"

	// CookieSameSiteLax sets the cookie to be sent along with "same-site"
	// requests, and with "cross-site" top-level navigations.
	CookieSameSiteLax CookieSameSite = "Lax"

	// CookieSameSiteNone sets the cookie to be sent in all contexts, i.e
	// potentially insecure third-party requests.
	CookieSameSiteNone CookieSameSite = "None"
)

type Credentials

type Credentials struct {
	Username string `js:"username"`
	Password string `js:"password"`
}

Credentials holds HTTP authentication credentials.

func NewCredentials

func NewCredentials() *Credentials

NewCredentials return a new Credentials.

func (*Credentials) Parse

func (c *Credentials) Parse(ctx context.Context, credentials goja.Value) error

Parse credentials details from a given goja credentials value.

type DOMElementState

type DOMElementState int

DOMElementState represents a DOM element state.

const (
	DOMElementStateAttached DOMElementState = iota
	DOMElementStateDetached
	DOMElementStateVisible
	DOMElementStateHidden
)

Valid DOM element states.

func (DOMElementState) MarshalJSON

func (s DOMElementState) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted JSON string.

func (DOMElementState) String

func (s DOMElementState) String() string

func (*DOMElementState) UnmarshalJSON

func (s *DOMElementState) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a quoted JSON string to the enum value.

type Device

type Device struct {
	Name              string   `js:"name"`
	UserAgent         string   `js:"userAgent"`
	Viewport          Viewport `js:"viewport"`
	DeviceScaleFactor float64  `js:"deviceScaleFactor"`
	IsMobile          bool     `js:"isMobile"`
	HasTouch          bool     `js:"hasTouch"`
}

Device represents an end-user device (computer, tablet, phone etc.)

type DocumentInfo

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

type ElementHandle

type ElementHandle struct {
	BaseJSHandle
	// contains filtered or unexported fields
}

ElementHandle represents a HTML element JS object inside an execution context.

func (*ElementHandle) AsElement

func (h *ElementHandle) AsElement() *ElementHandle

AsElement returns this element handle.

func (*ElementHandle) BoundingBox

func (h *ElementHandle) BoundingBox() *Rect

BoundingBox returns this element's bounding box.

func (*ElementHandle) Check

func (h *ElementHandle) Check(opts goja.Value)

Check scrolls element into view, and if it's an input element of type checkbox that is unchecked, clicks on it to mark it as checked.

func (*ElementHandle) Click

Click scrolls element into view and clicks in the center of the element TODO: look into making more robust using retries (see: https://github.com/microsoft/playwright/blob/master/src/server/dom.ts#L298)

func (*ElementHandle) ContentFrame

func (h *ElementHandle) ContentFrame() (*Frame, error)

ContentFrame returns the frame that contains this element.

func (*ElementHandle) Dblclick

func (h *ElementHandle) Dblclick(opts goja.Value)

func (*ElementHandle) DispatchEvent

func (h *ElementHandle) DispatchEvent(typ string, eventInit any) error

DispatchEvent dispatches a DOM event to the element.

func (*ElementHandle) Fill

func (h *ElementHandle) Fill(value string, opts goja.Value)

func (*ElementHandle) Focus

func (h *ElementHandle) Focus()

Focus scrolls element into view and focuses the element.

func (*ElementHandle) GetAttribute

func (h *ElementHandle) GetAttribute(name string) any

GetAttribute retrieves the value of specified element attribute.

func (*ElementHandle) Hover

func (h *ElementHandle) Hover(opts goja.Value)

Hover scrolls element into view and hovers over its center point.

func (*ElementHandle) InnerHTML

func (h *ElementHandle) InnerHTML() string

InnerHTML returns the inner HTML of the element.

func (*ElementHandle) InnerText

func (h *ElementHandle) InnerText() string

InnerText returns the inner text of the element.

func (*ElementHandle) InputValue

func (h *ElementHandle) InputValue(opts goja.Value) string

func (*ElementHandle) IsChecked

func (h *ElementHandle) IsChecked() bool

IsChecked checks if a checkbox or radio is checked.

func (*ElementHandle) IsDisabled

func (h *ElementHandle) IsDisabled() bool

IsDisabled checks if the element is disabled.

func (*ElementHandle) IsEditable

func (h *ElementHandle) IsEditable() bool

IsEditable checks if the element is editable.

func (*ElementHandle) IsEnabled

func (h *ElementHandle) IsEnabled() bool

IsEnabled checks if the element is enabled.

func (*ElementHandle) IsHidden

func (h *ElementHandle) IsHidden() bool

IsHidden checks if the element is hidden.

func (*ElementHandle) IsVisible

func (h *ElementHandle) IsVisible() bool

IsVisible checks if the element is visible.

func (*ElementHandle) OwnerFrame

func (h *ElementHandle) OwnerFrame() (*Frame, error)

OwnerFrame returns the frame containing this element.

func (*ElementHandle) Press

func (h *ElementHandle) Press(key string, opts goja.Value)

func (*ElementHandle) Query

func (h *ElementHandle) Query(selector string, strict bool) (*ElementHandle, error)

Query runs "element.querySelector" within the page. If no element matches the selector, the return value resolves to "null".

func (*ElementHandle) QueryAll

func (h *ElementHandle) QueryAll(selector string) ([]*ElementHandle, error)

QueryAll queries element subtree for matching elements. If no element matches the selector, the return value resolves to "null".

func (*ElementHandle) Screenshot

Screenshot will instruct Chrome to save a screenshot of the current element and save it to specified file.

func (*ElementHandle) ScrollIntoViewIfNeeded

func (h *ElementHandle) ScrollIntoViewIfNeeded(opts goja.Value)

func (*ElementHandle) SelectOption

func (h *ElementHandle) SelectOption(values goja.Value, opts goja.Value) []string

func (*ElementHandle) SelectText

func (h *ElementHandle) SelectText(opts goja.Value)

func (*ElementHandle) SetChecked

func (h *ElementHandle) SetChecked(checked bool, opts goja.Value)

SetChecked checks or unchecks an element.

func (*ElementHandle) SetInputFiles

func (h *ElementHandle) SetInputFiles(files goja.Value, opts goja.Value) error

SetInputFiles sets the given files into the input file element.

func (*ElementHandle) Tap

Tap scrolls element into view and taps in the center of the element.

func (*ElementHandle) TextContent

func (h *ElementHandle) TextContent() string

func (*ElementHandle) Timeout added in v1.4.0

func (h *ElementHandle) Timeout() time.Duration

Timeout will return the default timeout or the one set by the user. It's an internal method not to be exposed as a JS API.

func (*ElementHandle) Type

func (h *ElementHandle) Type(text string, opts goja.Value)

Type scrolls element into view, focuses element and types text.

func (*ElementHandle) Uncheck

func (h *ElementHandle) Uncheck(opts goja.Value)

Uncheck scrolls element into view, and if it's an input element of type checkbox that is already checked, clicks on it to mark it as unchecked.

func (*ElementHandle) WaitForElementState

func (h *ElementHandle) WaitForElementState(state string, opts goja.Value)

func (*ElementHandle) WaitForSelector

func (h *ElementHandle) WaitForSelector(selector string, opts goja.Value) (*ElementHandle, error)

WaitForSelector waits for the selector to appear in the DOM.

type ElementHandleBaseOptions

type ElementHandleBaseOptions struct {
	Force       bool          `json:"force"`
	NoWaitAfter bool          `json:"noWaitAfter"`
	Timeout     time.Duration `json:"timeout"`
}

func NewElementHandleBaseOptions

func NewElementHandleBaseOptions(defaultTimeout time.Duration) *ElementHandleBaseOptions

func (*ElementHandleBaseOptions) Parse

type ElementHandleBasePointerOptions

type ElementHandleBasePointerOptions struct {
	ElementHandleBaseOptions
	Position *Position `json:"position"`
	Trial    bool      `json:"trial"`
}

func NewElementHandleBasePointerOptions

func NewElementHandleBasePointerOptions(defaultTimeout time.Duration) *ElementHandleBasePointerOptions

func (*ElementHandleBasePointerOptions) Parse

type ElementHandleCheckOptions

type ElementHandleCheckOptions struct {
	ElementHandleBasePointerOptions
}

func NewElementHandleCheckOptions

func NewElementHandleCheckOptions(defaultTimeout time.Duration) *ElementHandleCheckOptions

func (*ElementHandleCheckOptions) Parse

type ElementHandleClickOptions

type ElementHandleClickOptions struct {
	ElementHandleBasePointerOptions
	Button     string   `json:"button"`
	ClickCount int64    `json:"clickCount"`
	Delay      int64    `json:"delay"`
	Modifiers  []string `json:"modifiers"`
}

func NewElementHandleClickOptions

func NewElementHandleClickOptions(defaultTimeout time.Duration) *ElementHandleClickOptions

func (*ElementHandleClickOptions) Parse

func (*ElementHandleClickOptions) ToMouseClickOptions

func (o *ElementHandleClickOptions) ToMouseClickOptions() *MouseClickOptions

type ElementHandleDblclickOptions

type ElementHandleDblclickOptions struct {
	ElementHandleBasePointerOptions
	Button    string   `json:"button"`
	Delay     int64    `json:"delay"`
	Modifiers []string `json:"modifiers"`
}

func NewElementHandleDblclickOptions

func NewElementHandleDblclickOptions(defaultTimeout time.Duration) *ElementHandleDblclickOptions

func (*ElementHandleDblclickOptions) Parse

func (*ElementHandleDblclickOptions) ToMouseClickOptions

func (o *ElementHandleDblclickOptions) ToMouseClickOptions() *MouseClickOptions

type ElementHandleDispatchEventOptions added in v0.4.0

type ElementHandleDispatchEventOptions struct {
	*ElementHandleBaseOptions
}

ElementHandleDispatchEventOptions are options for ElementHandle.dispatchEvent.

func NewElementHandleDispatchEventOptions added in v0.4.0

func NewElementHandleDispatchEventOptions(defaultTimeout time.Duration) *ElementHandleDispatchEventOptions

NewElementHandleDispatchEventOptions returns a new ElementHandleDispatchEventOptions.

type ElementHandleHoverOptions

type ElementHandleHoverOptions struct {
	ElementHandleBasePointerOptions
	Modifiers []string `json:"modifiers"`
}

func NewElementHandleHoverOptions

func NewElementHandleHoverOptions(defaultTimeout time.Duration) *ElementHandleHoverOptions

func (*ElementHandleHoverOptions) Parse

type ElementHandlePressOptions

type ElementHandlePressOptions struct {
	Delay       int64         `json:"delay"`
	NoWaitAfter bool          `json:"noWaitAfter"`
	Timeout     time.Duration `json:"timeout"`
}

func NewElementHandlePressOptions

func NewElementHandlePressOptions(defaultTimeout time.Duration) *ElementHandlePressOptions

func (*ElementHandlePressOptions) Parse

func (*ElementHandlePressOptions) ToBaseOptions

type ElementHandleScreenshotOptions

type ElementHandleScreenshotOptions struct {
	Path           string        `json:"path"`
	Format         ImageFormat   `json:"format"`
	OmitBackground bool          `json:"omitBackground"`
	Quality        int64         `json:"quality"`
	Timeout        time.Duration `json:"timeout"`
}

func NewElementHandleScreenshotOptions

func NewElementHandleScreenshotOptions(defaultTimeout time.Duration) *ElementHandleScreenshotOptions

func (*ElementHandleScreenshotOptions) Parse

type ElementHandleSetCheckedOptions

type ElementHandleSetCheckedOptions struct {
	ElementHandleBasePointerOptions
	Strict bool `json:"strict"`
}

func NewElementHandleSetCheckedOptions

func NewElementHandleSetCheckedOptions(defaultTimeout time.Duration) *ElementHandleSetCheckedOptions

func (*ElementHandleSetCheckedOptions) Parse

type ElementHandleSetInputFilesOptions added in v1.4.0

type ElementHandleSetInputFilesOptions struct {
	ElementHandleBaseOptions
}

ElementHandleSetInputFilesOptions are options for ElementHandle.SetInputFiles.

func NewElementHandleSetInputFilesOptions added in v1.4.0

func NewElementHandleSetInputFilesOptions(defaultTimeout time.Duration) *ElementHandleSetInputFilesOptions

NewElementHandleSetInputFilesOptions creates a new ElementHandleSetInputFilesOption.

func (*ElementHandleSetInputFilesOptions) Parse added in v1.4.0

Parse parses the ElementHandleSetInputFilesOption from the given opts.

type ElementHandleTapOptions

type ElementHandleTapOptions struct {
	ElementHandleBasePointerOptions
	Modifiers []string `json:"modifiers"`
}

func NewElementHandleTapOptions

func NewElementHandleTapOptions(defaultTimeout time.Duration) *ElementHandleTapOptions

func (*ElementHandleTapOptions) Parse

func (o *ElementHandleTapOptions) Parse(ctx context.Context, opts goja.Value) error

type ElementHandleTypeOptions

type ElementHandleTypeOptions struct {
	Delay       int64         `json:"delay"`
	NoWaitAfter bool          `json:"noWaitAfter"`
	Timeout     time.Duration `json:"timeout"`
}

func NewElementHandleTypeOptions

func NewElementHandleTypeOptions(defaultTimeout time.Duration) *ElementHandleTypeOptions

func (*ElementHandleTypeOptions) Parse

func (*ElementHandleTypeOptions) ToBaseOptions

type ElementHandleWaitForElementStateOptions

type ElementHandleWaitForElementStateOptions struct {
	Timeout time.Duration `json:"timeout"`
}

func NewElementHandleWaitForElementStateOptions

func NewElementHandleWaitForElementStateOptions(defaultTimeout time.Duration) *ElementHandleWaitForElementStateOptions

func (*ElementHandleWaitForElementStateOptions) Parse

type EmulatedSize

type EmulatedSize struct {
	Viewport *Viewport
	Screen   *Screen
}

EmulatedSize represents the emulated viewport and screen sizes.

func NewEmulatedSize

func NewEmulatedSize(viewport *Viewport, screen *Screen) *EmulatedSize

NewEmulatedSize creates and returns a new EmulatedSize.

type Error

type Error string

Error is a common package error.

const (
	ErrUnexpectedRemoteObjectWithID Error = "cannot extract value when remote object ID is given"
	ErrChannelClosed                Error = "channel closed"
	ErrFrameDetached                Error = "frame detached"
	ErrJSHandleDisposed             Error = "JS handle is disposed"
	ErrJSHandleInvalid              Error = "JS handle is invalid"
	ErrTargetCrashed                Error = "Target has crashed"
	ErrTimedOut                     Error = "timed out"
	ErrWrongExecutionContext        Error = "JS handles can be evaluated only in the context they were created"
)

Error types.

func (Error) Error

func (e Error) Error() string

Error satisfies the builtin error interface.

type Event

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

Event as emitted by an EventEmiter.

type EventEmitter

type EventEmitter interface {
	// contains filtered or unexported methods
}

EventEmitter that all event emitters need to implement.

type ExecutionContext

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

ExecutionContext represents a JS execution context.

func NewExecutionContext

func NewExecutionContext(
	ctx context.Context, s session, f *Frame, id runtime.ExecutionContextID, l *log.Logger,
) *ExecutionContext

NewExecutionContext creates a new JS execution context.

func (*ExecutionContext) Eval added in v0.2.0

func (e *ExecutionContext) Eval(apiCtx context.Context, js string, args ...any) (any, error)

Eval evaluates the provided JavaScript within this execution context and returns a value or handle.

func (*ExecutionContext) EvalHandle added in v0.2.0

func (e *ExecutionContext) EvalHandle(apiCtx context.Context, js string, args ...any) (JSHandleAPI, error)

EvalHandle evaluates the provided JavaScript within this execution context and returns a JSHandle.

func (*ExecutionContext) Frame

func (e *ExecutionContext) Frame() *Frame

Frame returns the frame that this execution context belongs to.

func (*ExecutionContext) ID added in v0.1.2

ID returns the CDP runtime ID of this execution context.

type File added in v1.4.0

type File struct {
	Name     string `json:"name"`
	Mimetype string `json:"mimeType"`
	Buffer   string `json:"buffer"`
}

File is the descriptor of a single file.

type Files added in v1.4.0

type Files struct {
	Payload []*File `json:"payload"`
}

Files is the input parameter for ElementHandle.SetInputFiles.

func (*Files) Parse added in v1.4.0

func (f *Files) Parse(ctx context.Context, files goja.Value) error

Parse parses the Files struct from the given goja.Value.

type Frame

type Frame struct {
	BaseEventEmitter
	// contains filtered or unexported fields
}

Frame represents a frame in an HTML document.

func NewFrame

func NewFrame(
	ctx context.Context, m *FrameManager, parentFrame *Frame, frameID cdp.FrameID, log *log.Logger,
) *Frame

NewFrame creates a new HTML document frame.

func (*Frame) Check

func (f *Frame) Check(selector string, opts goja.Value)

Check clicks the first element found that matches selector.

func (*Frame) ChildFrames

func (f *Frame) ChildFrames() []*Frame

ChildFrames returns a list of child frames.

func (*Frame) Click

func (f *Frame) Click(selector string, opts *FrameClickOptions) error

Click clicks the first element found that matches selector.

func (*Frame) Content

func (f *Frame) Content() string

Content returns the HTML content of the frame.

func (*Frame) Dblclick

func (f *Frame) Dblclick(selector string, opts goja.Value)

Dblclick double clicks an element matching provided selector.

func (*Frame) DispatchEvent

func (f *Frame) DispatchEvent(selector, typ string, eventInit any, opts *FrameDispatchEventOptions) error

DispatchEvent dispatches an event for the first element matching the selector.

func (*Frame) Evaluate

func (f *Frame) Evaluate(pageFunc string, args ...any) any

Evaluate will evaluate provided page function within an execution context.

func (*Frame) EvaluateGlobal added in v1.3.0

func (f *Frame) EvaluateGlobal(ctx context.Context, js string) error

EvaluateGlobal will evaluate the given JS code in the global object.

func (*Frame) EvaluateHandle

func (f *Frame) EvaluateHandle(pageFunc string, args ...any) (handle JSHandleAPI, _ error)

EvaluateHandle will evaluate provided page function within an execution context.

func (*Frame) EvaluateWithContext added in v1.0.0

func (f *Frame) EvaluateWithContext(ctx context.Context, pageFunc string, args ...any) (any, error)

EvaluateWithContext will evaluate provided page function within an execution context. The passed in context will be used instead of the frame's context. The context must be a derivative of one that contains the goja runtime.

func (*Frame) Fill

func (f *Frame) Fill(selector, value string, opts goja.Value)

Fill fills out the first element found that matches the selector.

func (*Frame) Focus

func (f *Frame) Focus(selector string, opts goja.Value)

Focus focuses on the first element that matches the selector.

func (*Frame) FrameElement

func (f *Frame) FrameElement() (*ElementHandle, error)

FrameElement returns the element handle for the frame.

func (*Frame) GetAttribute

func (f *Frame) GetAttribute(selector, name string, opts goja.Value) any

GetAttribute of the first element found that matches the selector.

func (*Frame) Goto

func (f *Frame) Goto(url string, opts *FrameGotoOptions) (*Response, error)

Goto will navigate the frame to the specified URL and return a HTTP response object.

func (*Frame) Hover

func (f *Frame) Hover(selector string, opts goja.Value)

Hover moves the pointer over the first element that matches the selector.

func (*Frame) ID

func (f *Frame) ID() string

ID returns the frame id.

func (*Frame) InnerHTML

func (f *Frame) InnerHTML(selector string, opts goja.Value) string

InnerHTML returns the innerHTML attribute of the first element found that matches the selector.

func (*Frame) InnerText

func (f *Frame) InnerText(selector string, opts goja.Value) string

InnerText returns the inner text of the first element found that matches the selector.

func (*Frame) InputValue

func (f *Frame) InputValue(selector string, opts goja.Value) string

InputValue returns the input value of the first element found that matches the selector.

func (*Frame) IsChecked

func (f *Frame) IsChecked(selector string, opts goja.Value) bool

IsChecked returns true if the first element that matches the selector is checked. Otherwise, returns false.

func (*Frame) IsDetached

func (f *Frame) IsDetached() bool

IsDetached returns whether the frame is detached or not.

func (*Frame) IsDisabled

func (f *Frame) IsDisabled(selector string, opts goja.Value) bool

IsDisabled returns true if the first element that matches the selector is disabled. Otherwise, returns false.

func (*Frame) IsEditable

func (f *Frame) IsEditable(selector string, opts goja.Value) bool

IsEditable returns true if the first element that matches the selector is editable. Otherwise, returns false.

func (*Frame) IsEnabled

func (f *Frame) IsEnabled(selector string, opts goja.Value) bool

IsEnabled returns true if the first element that matches the selector is enabled. Otherwise, returns false.

func (*Frame) IsHidden

func (f *Frame) IsHidden(selector string, opts goja.Value) (bool, error)

IsHidden returns true if the first element that matches the selector is hidden. Otherwise, returns false.

func (*Frame) IsVisible

func (f *Frame) IsVisible(selector string, opts goja.Value) (bool, error)

IsVisible returns true if the first element that matches the selector is visible. Otherwise, returns false.

func (*Frame) LoaderID

func (f *Frame) LoaderID() string

LoaderID returns the ID of the frame that loaded this frame.

func (*Frame) Locator added in v0.4.0

func (f *Frame) Locator(selector string, opts goja.Value) *Locator

Locator creates and returns a new locator for this frame.

func (*Frame) Name

func (f *Frame) Name() string

Name returns the frame name.

func (*Frame) NavigationTimeout added in v1.4.0

func (f *Frame) NavigationTimeout() time.Duration

NavigationTimeout returns the navigation timeout of the frame. It's an internal method not to be exposed as a JS API.

func (*Frame) Page

func (f *Frame) Page() *Page

Page returns page that owns frame.

func (*Frame) ParentFrame

func (f *Frame) ParentFrame() *Frame

ParentFrame returns the parent frame, if one exists.

func (*Frame) Press

func (f *Frame) Press(selector, key string, opts goja.Value)

Press presses the given key for the first element found that matches the selector.

func (*Frame) Query

func (f *Frame) Query(selector string, strict bool) (*ElementHandle, error)

Query runs a selector query against the document tree, returning the first matching element or "null" if no match is found.

func (*Frame) QueryAll

func (f *Frame) QueryAll(selector string) ([]*ElementHandle, error)

QueryAll runs a selector query against the document tree, returning all matching elements.

func (*Frame) Referrer added in v1.4.0

func (f *Frame) Referrer() string

Referrer returns the referrer of the frame from the network manager of the frame's session. It's an internal method not to be exposed as a JS API.

func (*Frame) SelectOption

func (f *Frame) SelectOption(selector string, values goja.Value, opts goja.Value) []string

SelectOption selects the given options and returns the array of option values of the first element found that matches the selector.

func (*Frame) SetContent

func (f *Frame) SetContent(html string, opts goja.Value)

SetContent replaces the entire HTML document content.

func (*Frame) SetInputFiles

func (f *Frame) SetInputFiles(selector string, files goja.Value, opts goja.Value) error

SetInputFiles sets input files for the selected element.

func (*Frame) Tap

func (f *Frame) Tap(selector string, opts *FrameTapOptions) error

Tap the first element that matches the selector.

func (*Frame) TextContent

func (f *Frame) TextContent(selector string, opts goja.Value) string

TextContent returns the textContent attribute of the first element found that matches the selector.

func (*Frame) Timeout added in v1.4.0

func (f *Frame) Timeout() time.Duration

Timeout will return the default timeout or the one set by the user. It's an internal method not to be exposed as a JS API.

func (*Frame) Title

func (f *Frame) Title() string

Title returns the title of the frame.

func (*Frame) Type

func (f *Frame) Type(selector, text string, opts goja.Value)

Type text on the first element found matches the selector.

func (*Frame) URL

func (f *Frame) URL() string

URL returns the frame URL.

func (*Frame) Uncheck

func (f *Frame) Uncheck(selector string, opts goja.Value)

Uncheck the first found element that matches the selector.

func (*Frame) WaitForFunction

func (f *Frame) WaitForFunction(js string, opts *FrameWaitForFunctionOptions, jsArgs ...any) (any, error)

WaitForFunction waits for the given predicate to return a truthy value.

func (*Frame) WaitForLoadState

func (f *Frame) WaitForLoadState(state string, opts goja.Value)

WaitForLoadState waits for the given load state to be reached. This will unblock if that lifecycle event has already been received.

func (*Frame) WaitForNavigation

func (f *Frame) WaitForNavigation(opts *FrameWaitForNavigationOptions) (*Response, error)

WaitForNavigation waits for the given navigation lifecycle event to happen.

func (*Frame) WaitForSelector

func (f *Frame) WaitForSelector(selector string, opts goja.Value) (*ElementHandle, error)

WaitForSelector waits for the given selector to match the waiting criteria.

func (*Frame) WaitForTimeout

func (f *Frame) WaitForTimeout(timeout int64)

WaitForTimeout waits the specified amount of milliseconds.

type FrameBaseOptions

type FrameBaseOptions struct {
	Timeout time.Duration `json:"timeout"`
	Strict  bool          `json:"strict"`
}

func NewFrameBaseOptions

func NewFrameBaseOptions(defaultTimeout time.Duration) *FrameBaseOptions

func (*FrameBaseOptions) Parse

func (o *FrameBaseOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameCheckOptions

type FrameCheckOptions struct {
	ElementHandleBasePointerOptions
	Strict bool `json:"strict"`
}

func NewFrameCheckOptions

func NewFrameCheckOptions(defaultTimeout time.Duration) *FrameCheckOptions

func (*FrameCheckOptions) Parse

func (o *FrameCheckOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameClickOptions

type FrameClickOptions struct {
	ElementHandleClickOptions
	Strict bool `json:"strict"`
}

func NewFrameClickOptions

func NewFrameClickOptions(defaultTimeout time.Duration) *FrameClickOptions

func (*FrameClickOptions) Parse

func (o *FrameClickOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameDblclickOptions

type FrameDblclickOptions struct {
	ElementHandleDblclickOptions
	Strict bool `json:"strict"`
}

func NewFrameDblClickOptions

func NewFrameDblClickOptions(defaultTimeout time.Duration) *FrameDblclickOptions

func (*FrameDblclickOptions) Parse

func (o *FrameDblclickOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameDispatchEventOptions added in v0.4.0

type FrameDispatchEventOptions struct {
	*FrameBaseOptions
}

FrameDispatchEventOptions are options for Frame.dispatchEvent.

func NewFrameDispatchEventOptions added in v0.4.0

func NewFrameDispatchEventOptions(defaultTimeout time.Duration) *FrameDispatchEventOptions

NewFrameDispatchEventOptions returns a new FrameDispatchEventOptions.

type FrameFillOptions

type FrameFillOptions struct {
	ElementHandleBaseOptions
	Strict bool `json:"strict"`
}

func NewFrameFillOptions

func NewFrameFillOptions(defaultTimeout time.Duration) *FrameFillOptions

func (*FrameFillOptions) Parse

func (o *FrameFillOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameGotoOptions

type FrameGotoOptions struct {
	Referer   string         `json:"referer"`
	Timeout   time.Duration  `json:"timeout"`
	WaitUntil LifecycleEvent `json:"waitUntil" js:"waitUntil"`
}

func NewFrameGotoOptions

func NewFrameGotoOptions(defaultReferer string, defaultTimeout time.Duration) *FrameGotoOptions

func (*FrameGotoOptions) Parse

func (o *FrameGotoOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameHoverOptions

type FrameHoverOptions struct {
	ElementHandleHoverOptions
	Strict bool `json:"strict"`
}

func NewFrameHoverOptions

func NewFrameHoverOptions(defaultTimeout time.Duration) *FrameHoverOptions

func (*FrameHoverOptions) Parse

func (o *FrameHoverOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameInnerHTMLOptions

type FrameInnerHTMLOptions struct {
	FrameBaseOptions
}

func NewFrameInnerHTMLOptions

func NewFrameInnerHTMLOptions(defaultTimeout time.Duration) *FrameInnerHTMLOptions

func (*FrameInnerHTMLOptions) Parse

func (o *FrameInnerHTMLOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameInnerTextOptions

type FrameInnerTextOptions struct {
	FrameBaseOptions
}

func NewFrameInnerTextOptions

func NewFrameInnerTextOptions(defaultTimeout time.Duration) *FrameInnerTextOptions

func (*FrameInnerTextOptions) Parse

func (o *FrameInnerTextOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameInputValueOptions

type FrameInputValueOptions struct {
	FrameBaseOptions
}

func NewFrameInputValueOptions

func NewFrameInputValueOptions(defaultTimeout time.Duration) *FrameInputValueOptions

func (*FrameInputValueOptions) Parse

func (o *FrameInputValueOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameIsCheckedOptions

type FrameIsCheckedOptions struct {
	FrameBaseOptions
}

func NewFrameIsCheckedOptions

func NewFrameIsCheckedOptions(defaultTimeout time.Duration) *FrameIsCheckedOptions

func (*FrameIsCheckedOptions) Parse

func (o *FrameIsCheckedOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameIsDisabledOptions

type FrameIsDisabledOptions struct {
	FrameBaseOptions
}

func NewFrameIsDisabledOptions

func NewFrameIsDisabledOptions(defaultTimeout time.Duration) *FrameIsDisabledOptions

func (*FrameIsDisabledOptions) Parse

func (o *FrameIsDisabledOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameIsEditableOptions

type FrameIsEditableOptions struct {
	FrameBaseOptions
}

func NewFrameIsEditableOptions

func NewFrameIsEditableOptions(defaultTimeout time.Duration) *FrameIsEditableOptions

func (*FrameIsEditableOptions) Parse

func (o *FrameIsEditableOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameIsEnabledOptions

type FrameIsEnabledOptions struct {
	FrameBaseOptions
}

func NewFrameIsEnabledOptions

func NewFrameIsEnabledOptions(defaultTimeout time.Duration) *FrameIsEnabledOptions

func (*FrameIsEnabledOptions) Parse

func (o *FrameIsEnabledOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameIsHiddenOptions

type FrameIsHiddenOptions struct {
	Strict bool `json:"strict"`
}

func NewFrameIsHiddenOptions

func NewFrameIsHiddenOptions() *FrameIsHiddenOptions

NewFrameIsHiddenOptions creates and returns a new instance of FrameIsHiddenOptions.

func (*FrameIsHiddenOptions) Parse

func (o *FrameIsHiddenOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameIsVisibleOptions

type FrameIsVisibleOptions struct {
	Strict bool `json:"strict"`
}

func NewFrameIsVisibleOptions

func NewFrameIsVisibleOptions() *FrameIsVisibleOptions

NewFrameIsVisibleOptions creates and returns a new instance of FrameIsVisibleOptions.

func (*FrameIsVisibleOptions) Parse

func (o *FrameIsVisibleOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameLifecycleEvent added in v1.0.0

type FrameLifecycleEvent struct {
	// URL is the URL of the frame that emitted the event.
	URL string

	// Event is the lifecycle event that occurred.
	Event LifecycleEvent
}

FrameLifecycleEvent is emitted when a frame lifecycle event occurs.

type FrameManager

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

FrameManager manages all frames in a page and their life-cycles, it's a purely internal component.

func NewFrameManager

func NewFrameManager(
	ctx context.Context,
	s session,
	p *Page,
	ts *TimeoutSettings,
	l *log.Logger,
) *FrameManager

NewFrameManager creates a new HTML document frame manager.

func (*FrameManager) Frames

func (m *FrameManager) Frames() []*Frame

Frames returns a list of frames on the page.

func (*FrameManager) ID added in v0.1.3

func (m *FrameManager) ID() int64

ID returns the unique ID of a FrameManager value.

func (*FrameManager) MainFrame

func (m *FrameManager) MainFrame() *Frame

MainFrame returns the main frame of the page.

func (*FrameManager) NavigateFrame

func (m *FrameManager) NavigateFrame(frame *Frame, url string, parsedOpts *FrameGotoOptions) (*Response, error)

NavigateFrame will navigate specified frame to specified URL.

func (*FrameManager) Page

func (m *FrameManager) Page() *Page

Page returns the page that this frame manager belongs to.

type FramePressOptions

type FramePressOptions struct {
	ElementHandlePressOptions
	Strict bool `json:"strict"`
}

func NewFramePressOptions

func NewFramePressOptions(defaultTimeout time.Duration) *FramePressOptions

func (*FramePressOptions) ToKeyboardOptions

func (o *FramePressOptions) ToKeyboardOptions() *KeyboardOptions

type FrameSelectOptionOptions

type FrameSelectOptionOptions struct {
	ElementHandleBaseOptions
	Strict bool `json:"strict"`
}

func NewFrameSelectOptionOptions

func NewFrameSelectOptionOptions(defaultTimeout time.Duration) *FrameSelectOptionOptions

func (*FrameSelectOptionOptions) Parse

type FrameSession

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

FrameSession is used for managing a frame's life-cycle, or in other words its full session. It manages all the event listening while deferring the state storage to the Frame and FrameManager structs.

func NewFrameSession

func NewFrameSession(
	ctx context.Context, s session, p *Page, parent *FrameSession, tid target.ID, l *log.Logger,
) (_ *FrameSession, err error)

NewFrameSession initializes and returns a new FrameSession.

type FrameSetContentOptions

type FrameSetContentOptions struct {
	Timeout   time.Duration  `json:"timeout"`
	WaitUntil LifecycleEvent `json:"waitUntil" js:"waitUntil"`
}

func NewFrameSetContentOptions

func NewFrameSetContentOptions(defaultTimeout time.Duration) *FrameSetContentOptions

func (*FrameSetContentOptions) Parse

func (o *FrameSetContentOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameSetInputFilesOptions added in v1.4.0

type FrameSetInputFilesOptions struct {
	ElementHandleSetInputFilesOptions
	Strict bool `json:"strict"`
}

FrameSetInputFilesOptions are options for Frame.setInputFiles.

func NewFrameSetInputFilesOptions added in v1.4.0

func NewFrameSetInputFilesOptions(defaultTimeout time.Duration) *FrameSetInputFilesOptions

NewFrameSetInputFilesOptions creates a new FrameSetInputFilesOptions.

func (*FrameSetInputFilesOptions) Parse added in v1.4.0

Parse parses FrameSetInputFilesOptions from goja.Value.

type FrameTapOptions

type FrameTapOptions struct {
	ElementHandleBasePointerOptions
	Modifiers []string `json:"modifiers"`
	Strict    bool     `json:"strict"`
}

func NewFrameTapOptions

func NewFrameTapOptions(defaultTimeout time.Duration) *FrameTapOptions

func (*FrameTapOptions) Parse

func (o *FrameTapOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameTextContentOptions

type FrameTextContentOptions struct {
	FrameBaseOptions
}

func NewFrameTextContentOptions

func NewFrameTextContentOptions(defaultTimeout time.Duration) *FrameTextContentOptions

func (*FrameTextContentOptions) Parse

func (o *FrameTextContentOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameTypeOptions

type FrameTypeOptions struct {
	ElementHandleTypeOptions
	Strict bool `json:"strict"`
}

func NewFrameTypeOptions

func NewFrameTypeOptions(defaultTimeout time.Duration) *FrameTypeOptions

func (*FrameTypeOptions) ToKeyboardOptions

func (o *FrameTypeOptions) ToKeyboardOptions() *KeyboardOptions

type FrameUncheckOptions

type FrameUncheckOptions struct {
	ElementHandleBasePointerOptions
	Strict bool `json:"strict"`
}

func NewFrameUncheckOptions

func NewFrameUncheckOptions(defaultTimeout time.Duration) *FrameUncheckOptions

func (*FrameUncheckOptions) Parse

func (o *FrameUncheckOptions) Parse(ctx context.Context, opts goja.Value) error

type FrameWaitForFunctionOptions

type FrameWaitForFunctionOptions struct {
	Polling  PollingType   `json:"polling"`
	Interval int64         `json:"interval"`
	Timeout  time.Duration `json:"timeout"`
}

func NewFrameWaitForFunctionOptions

func NewFrameWaitForFunctionOptions(defaultTimeout time.Duration) *FrameWaitForFunctionOptions

func (*FrameWaitForFunctionOptions) Parse

Parse JavaScript waitForFunction options.

type FrameWaitForLoadStateOptions

type FrameWaitForLoadStateOptions struct {
	Timeout time.Duration `json:"timeout"`
}

func NewFrameWaitForLoadStateOptions

func NewFrameWaitForLoadStateOptions(defaultTimeout time.Duration) *FrameWaitForLoadStateOptions

func (*FrameWaitForLoadStateOptions) Parse

type FrameWaitForNavigationOptions

type FrameWaitForNavigationOptions struct {
	URL       string         `json:"url"`
	WaitUntil LifecycleEvent `json:"waitUntil" js:"waitUntil"`
	Timeout   time.Duration  `json:"timeout"`
}

func NewFrameWaitForNavigationOptions

func NewFrameWaitForNavigationOptions(defaultTimeout time.Duration) *FrameWaitForNavigationOptions

func (*FrameWaitForNavigationOptions) Parse

type FrameWaitForSelectorOptions

type FrameWaitForSelectorOptions struct {
	State   DOMElementState `json:"state"`
	Strict  bool            `json:"strict"`
	Timeout time.Duration   `json:"timeout"`
}

func NewFrameWaitForSelectorOptions

func NewFrameWaitForSelectorOptions(defaultTimeout time.Duration) *FrameWaitForSelectorOptions

func (*FrameWaitForSelectorOptions) Parse

type Geolocation

type Geolocation struct {
	Latitude  float64 `js:"latitude"`
	Longitude float64 `js:"longitude"`
	Accurracy float64 `js:"accurracy"`
}

Geolocation represents a geolocation.

func NewGeolocation

func NewGeolocation() *Geolocation

NewGeolocation creates a new instance of Geolocation.

func (*Geolocation) Parse

func (g *Geolocation) Parse(ctx context.Context, opts goja.Value) error

Parse parses the geolocation options.

type GrantPermissionsOptions added in v1.2.0

type GrantPermissionsOptions struct {
	Origin string
}

GrantPermissionsOptions is used by BrowserContext.GrantPermissions.

func NewGrantPermissionsOptions added in v1.2.0

func NewGrantPermissionsOptions() *GrantPermissionsOptions

NewGrantPermissionsOptions returns a new GrantPermissionsOptions.

func (*GrantPermissionsOptions) Parse added in v1.2.0

func (g *GrantPermissionsOptions) Parse(ctx context.Context, opts goja.Value)

Parse parses the options from opts if opts exists in the Goja runtime.

type HTTPHeader added in v1.2.0

type HTTPHeader struct {
	Name  string `json:"name"`
	Value string `json:"value"`
}

HTTPHeader is a single HTTP header.

type HTTPMessageSize added in v1.2.0

type HTTPMessageSize struct {
	Headers int64 `json:"headers"`
	Body    int64 `json:"body"`
}

HTTPMessageSize are the sizes in bytes of the HTTP message header and body.

func (HTTPMessageSize) Total added in v1.2.0

func (s HTTPMessageSize) Total() int64

Total returns the total size in bytes of the HTTP message.

type Hook

type Hook func(context.Context)

type HookID

type HookID int
const (
	HookApplySlowMo HookID = iota
)

type Hooks

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

func GetHooks

func GetHooks(ctx context.Context) *Hooks

func NewHooks

func NewHooks() *Hooks

func (*Hooks) Get

func (h *Hooks) Get(id HookID) Hook

func (*Hooks) Register

func (h *Hooks) Register(id HookID, hook Hook)

type ImageFormat

type ImageFormat string

ImageFormat represents an image file format.

const (
	ImageFormatJPEG ImageFormat = "jpeg"
	ImageFormatPNG  ImageFormat = "png"
)

Valid image format options.

func (ImageFormat) MarshalJSON

func (f ImageFormat) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted JSON string.

func (ImageFormat) String

func (f ImageFormat) String() string

func (*ImageFormat) UnmarshalJSON

func (f *ImageFormat) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a quoted JSON string to the enum value.

type JSHandleAPI added in v1.2.0

type JSHandleAPI interface {
	AsElement() *ElementHandle
	Dispose()
	Evaluate(pageFunc string, args ...any) any
	EvaluateHandle(pageFunc string, args ...any) (JSHandleAPI, error)
	GetProperties() (map[string]JSHandleAPI, error)
	JSONValue() (string, error)
	ObjectID() cdpruntime.RemoteObjectID
}

JSHandleAPI is the interface of an in-page JS object.

TODO: Find a way to move this to a concrete type. It's too difficult to do that right now because of the tests and the way we're using the JSHandleAPI interface.

type Keyboard

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

Keyboard represents a keyboard input device. Each Page has a publicly accessible Keyboard.

func NewKeyboard

func NewKeyboard(ctx context.Context, s session) *Keyboard

NewKeyboard returns a new keyboard with a "us" layout.

func (*Keyboard) Down

func (k *Keyboard) Down(key string)

Down sends a key down message to a session target.

func (*Keyboard) InsertText

func (k *Keyboard) InsertText(text string)

InsertText inserts a text without dispatching key events.

func (*Keyboard) Press

func (k *Keyboard) Press(key string, opts goja.Value)

Press sends a key press message to a session target. It delays the action if `Delay` option is specified. A press message consists of successive key down and up messages.

func (*Keyboard) Type

func (k *Keyboard) Type(text string, opts goja.Value)

Type sends a press message to a session target for each character in text. It delays the action if `Delay` option is specified.

It sends an insertText message if a character is not among valid characters in the keyboard's layout.

func (*Keyboard) Up

func (k *Keyboard) Up(key string)

Up sends a key up message to a session target.

type KeyboardOptions

type KeyboardOptions struct {
	Delay int64 `json:"delay"`
}

func NewKeyboardOptions

func NewKeyboardOptions() *KeyboardOptions

func (*KeyboardOptions) Parse

func (o *KeyboardOptions) Parse(ctx context.Context, opts goja.Value) error

type LifecycleEvent

type LifecycleEvent int

LifecycleEvent is a lifecycle event.

const (
	// LifecycleEventLoad is emitted when the page load event is fired.
	LifecycleEventLoad LifecycleEvent = iota

	// LifecycleEventDOMContentLoad is emitted when the DOMContentLoaded event is fired.
	LifecycleEventDOMContentLoad

	// LifecycleEventNetworkIdle is emitted when there are no more than 2 network connections for at least 500 ms.
	LifecycleEventNetworkIdle
)

func (LifecycleEvent) MarshalJSON

func (l LifecycleEvent) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted JSON string.

func (*LifecycleEvent) MarshalText added in v0.3.0

func (l *LifecycleEvent) MarshalText() ([]byte, error)

MarshalText returns the string representation of the enum value. It returns an error if the enum value is invalid.

func (LifecycleEvent) String

func (l LifecycleEvent) String() string

func (*LifecycleEvent) UnmarshalJSON

func (l *LifecycleEvent) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a quoted JSON string to the enum value.

func (*LifecycleEvent) UnmarshalText added in v0.3.0

func (l *LifecycleEvent) UnmarshalText(text []byte) error

UnmarshalText unmarshals a text representation to the enum value. It returns an error if given a wrong value.

type Locator added in v0.4.0

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

Locator represent a way to find element(s) on the page at any moment.

func NewLocator added in v0.4.0

func NewLocator(ctx context.Context, selector string, f *Frame, l *log.Logger) *Locator

NewLocator creates and returns a new locator.

func (*Locator) Check added in v0.4.0

func (l *Locator) Check(opts goja.Value)

Check on an element using locator's selector with strict mode on.

func (*Locator) Clear added in v1.3.0

func (l *Locator) Clear(opts *FrameFillOptions) error

Clear will clear the input field. This works with the Fill API and fills the input field with an empty string.

func (*Locator) Click added in v0.4.0

func (l *Locator) Click(opts *FrameClickOptions) error

Click on an element using locator's selector with strict mode on.

func (*Locator) Dblclick added in v0.4.0

func (l *Locator) Dblclick(opts goja.Value)

Dblclick double clicks on an element using locator's selector with strict mode on.

func (*Locator) DefaultTimeout added in v1.4.0

func (l *Locator) DefaultTimeout() time.Duration

DefaultTimeout returns the default timeout for the locator. This is an internal API and should not be used by users.

func (*Locator) DispatchEvent added in v0.4.0

func (l *Locator) DispatchEvent(typ string, eventInit any, opts *FrameDispatchEventOptions) error

DispatchEvent dispatches an event for the element matching the locator's selector with strict mode on.

func (*Locator) Fill added in v0.4.0

func (l *Locator) Fill(value string, opts goja.Value)

Fill out the element using locator's selector with strict mode on.

func (*Locator) Focus added in v0.4.0

func (l *Locator) Focus(opts goja.Value)

Focus on the element using locator's selector with strict mode on.

func (*Locator) GetAttribute added in v0.4.0

func (l *Locator) GetAttribute(name string, opts goja.Value) any

GetAttribute of the element using locator's selector with strict mode on.

func (*Locator) Hover added in v0.4.0

func (l *Locator) Hover(opts goja.Value)

Hover moves the pointer over the element that matches the locator's selector with strict mode on.

func (*Locator) InnerHTML added in v0.4.0

func (l *Locator) InnerHTML(opts goja.Value) string

InnerHTML returns the element's inner HTML that matches the locator's selector with strict mode on.

func (*Locator) InnerText added in v0.4.0

func (l *Locator) InnerText(opts goja.Value) string

InnerText returns the element's inner text that matches the locator's selector with strict mode on.

func (*Locator) InputValue added in v0.4.0

func (l *Locator) InputValue(opts goja.Value) string

InputValue returns the element's input value that matches the locator's selector with strict mode on.

func (*Locator) IsChecked added in v0.4.0

func (l *Locator) IsChecked(opts goja.Value) bool

IsChecked returns true if the element matches the locator's selector and is checked. Otherwise, returns false.

func (*Locator) IsDisabled added in v0.4.0

func (l *Locator) IsDisabled(opts goja.Value) bool

IsDisabled returns true if the element matches the locator's selector and is disabled. Otherwise, returns false.

func (*Locator) IsEditable added in v0.4.0

func (l *Locator) IsEditable(opts goja.Value) bool

IsEditable returns true if the element matches the locator's selector and is Editable. Otherwise, returns false.

func (*Locator) IsEnabled added in v0.4.0

func (l *Locator) IsEnabled(opts goja.Value) bool

IsEnabled returns true if the element matches the locator's selector and is Enabled. Otherwise, returns false.

func (*Locator) IsHidden added in v0.4.0

func (l *Locator) IsHidden() (bool, error)

IsHidden returns true if the element matches the locator's selector and is hidden. Otherwise, returns false.

func (*Locator) IsVisible added in v0.4.0

func (l *Locator) IsVisible() (bool, error)

IsVisible returns true if the element matches the locator's selector and is visible. Otherwise, returns false.

func (*Locator) Press added in v0.4.0

func (l *Locator) Press(key string, opts goja.Value)

Press the given key on the element found that matches the locator's selector with strict mode on.

func (*Locator) SelectOption added in v0.4.0

func (l *Locator) SelectOption(values goja.Value, opts goja.Value) []string

SelectOption filters option values of the first element that matches the locator's selector (with strict mode on), selects the options, and returns the filtered options.

func (*Locator) Tap added in v0.4.0

func (l *Locator) Tap(opts *FrameTapOptions) error

Tap the element found that matches the locator's selector with strict mode on.

func (*Locator) TextContent added in v0.4.0

func (l *Locator) TextContent(opts goja.Value) string

TextContent returns the element's text content that matches the locator's selector with strict mode on.

func (*Locator) Timeout added in v1.3.0

func (l *Locator) Timeout() time.Duration

Timeout will return the default timeout or the one set by the user.

func (*Locator) Type added in v0.4.0

func (l *Locator) Type(text string, opts goja.Value) error

Type text on the element found that matches the locator's selector with strict mode on.

func (*Locator) Uncheck added in v0.4.0

func (l *Locator) Uncheck(opts goja.Value)

Uncheck on an element using locator's selector with strict mode on.

func (*Locator) WaitFor added in v0.4.0

func (l *Locator) WaitFor(opts goja.Value)

WaitFor waits for the element matching the locator's selector with strict mode on.

type MediaType

type MediaType string

MediaType represents the type of media to emulate.

const (
	// MediaTypeScreen represents the screen media type.
	MediaTypeScreen MediaType = "screen"

	// MediaTypePrint represents the print media type.
	MediaTypePrint MediaType = "print"
)

type Mouse

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

Mouse represents a mouse input device.

func NewMouse

func NewMouse(ctx context.Context, s session, f *Frame, ts *TimeoutSettings, k *Keyboard) *Mouse

NewMouse creates a new mouse.

func (*Mouse) Click

func (m *Mouse) Click(x float64, y float64, opts goja.Value)

Click will trigger a series of MouseMove, MouseDown and MouseUp events in the browser.

func (*Mouse) DblClick

func (m *Mouse) DblClick(x float64, y float64, opts goja.Value)

func (*Mouse) Down

func (m *Mouse) Down(x float64, y float64, opts goja.Value)

Down will trigger a MouseDown event in the browser.

func (*Mouse) Move

func (m *Mouse) Move(x float64, y float64, opts goja.Value)

Move will trigger a MouseMoved event in the browser.

func (*Mouse) Up

func (m *Mouse) Up(x float64, y float64, opts goja.Value)

Up will trigger a MouseUp event in the browser.

type MouseClickOptions

type MouseClickOptions struct {
	Button     string `json:"button"`
	ClickCount int64  `json:"clickCount"`
	Delay      int64  `json:"delay"`
}

func NewMouseClickOptions

func NewMouseClickOptions() *MouseClickOptions

func (*MouseClickOptions) Parse

func (o *MouseClickOptions) Parse(ctx context.Context, opts goja.Value) error

func (*MouseClickOptions) ToMouseDownUpOptions

func (o *MouseClickOptions) ToMouseDownUpOptions() *MouseDownUpOptions

type MouseDblClickOptions

type MouseDblClickOptions struct {
	Button string `json:"button"`
	Delay  int64  `json:"delay"`
}

func NewMouseDblClickOptions

func NewMouseDblClickOptions() *MouseDblClickOptions

func (*MouseDblClickOptions) Parse

func (o *MouseDblClickOptions) Parse(ctx context.Context, opts goja.Value) error

func (*MouseDblClickOptions) ToMouseClickOptions added in v1.3.0

func (o *MouseDblClickOptions) ToMouseClickOptions() *MouseClickOptions

ToMouseClickOptions converts MouseDblClickOptions to a MouseClickOptions.

type MouseDownUpOptions

type MouseDownUpOptions struct {
	Button     string `json:"button"`
	ClickCount int64  `json:"clickCount"`
}

func NewMouseDownUpOptions

func NewMouseDownUpOptions() *MouseDownUpOptions

func (*MouseDownUpOptions) Parse

func (o *MouseDownUpOptions) Parse(ctx context.Context, opts goja.Value) error

type MouseMoveOptions

type MouseMoveOptions struct {
	Steps int64 `json:"steps"`
}

func NewMouseMoveOptions

func NewMouseMoveOptions() *MouseMoveOptions

func (*MouseMoveOptions) Parse

func (o *MouseMoveOptions) Parse(ctx context.Context, opts goja.Value) error
type NavigationEvent struct {
	// contains filtered or unexported fields
}

NavigationEvent is emitted when we receive a Page.frameNavigated or Page.navigatedWithinDocument CDP event. See: - https://chromedevtools.github.io/devtools-protocol/tot/Page/#event-frameNavigated - https://chromedevtools.github.io/devtools-protocol/tot/Page/#event-navigatedWithinDocument

type NetworkManager

type NetworkManager struct {
	BaseEventEmitter
	// contains filtered or unexported fields
}

NetworkManager manages all frames in HTML document.

func NewNetworkManager

func NewNetworkManager(
	ctx context.Context, customMetrics *k6ext.CustomMetrics, s session, fm *FrameManager, parent *NetworkManager,
) (*NetworkManager, error)

NewNetworkManager creates a new network manager.

func (*NetworkManager) Authenticate

func (m *NetworkManager) Authenticate(credentials *Credentials)

Authenticate sets HTTP authentication credentials to use.

func (*NetworkManager) ExtraHTTPHeaders

func (m *NetworkManager) ExtraHTTPHeaders() goja.Value

ExtraHTTPHeaders returns the currently set extra HTTP request headers.

func (*NetworkManager) SetCacheEnabled

func (m *NetworkManager) SetCacheEnabled(enabled bool)

SetCacheEnabled toggles cache on/off.

func (*NetworkManager) SetExtraHTTPHeaders

func (m *NetworkManager) SetExtraHTTPHeaders(headers network.Headers)

SetExtraHTTPHeaders sets extra HTTP request headers to be sent with every request.

func (*NetworkManager) SetOfflineMode

func (m *NetworkManager) SetOfflineMode(offline bool)

SetOfflineMode toggles offline mode on/off.

func (*NetworkManager) SetUserAgent

func (m *NetworkManager) SetUserAgent(userAgent string)

SetUserAgent overrides the browser user agent string.

func (*NetworkManager) ThrottleNetwork added in v1.2.0

func (m *NetworkManager) ThrottleNetwork(networkProfile NetworkProfile) error

ThrottleNetwork changes the network attributes in chrome to simulate slower networks e.g. a slow 3G connection.

type NetworkProfile added in v1.2.0

type NetworkProfile struct {
	// Minimum latency from request sent to response headers received (ms).
	Latency float64

	// Maximal aggregated download throughput (bytes/sec). -1 disables download throttling.
	Download float64

	// Maximal aggregated upload throughput (bytes/sec). -1 disables upload throttling.
	Upload float64
}

NetworkProfile is used in ThrottleNetwork.

func NewNetworkProfile added in v1.2.0

func NewNetworkProfile() NetworkProfile

NewNetworkProfile creates a non-throttled network profile.

type NewRequestParams added in v0.6.0

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

NewRequestParams are input parameters for NewRequest.

type Page

type Page struct {
	BaseEventEmitter

	Keyboard    *Keyboard
	Mouse       *Mouse
	Touchscreen *Touchscreen
	// contains filtered or unexported fields
}

Page stores Page/tab related context.

func NewPage

func NewPage(
	ctx context.Context,
	s session,
	bctx *BrowserContext,
	tid target.ID,
	opener *Page,
	bp bool,
	logger *log.Logger,
) (*Page, error)

NewPage creates a new browser page context.

func (*Page) BringToFront added in v0.1.2

func (p *Page) BringToFront()

BringToFront activates the browser tab for this page.

func (*Page) Check

func (p *Page) Check(selector string, opts goja.Value)

Check checks an element matching the provided selector.

func (*Page) Click

func (p *Page) Click(selector string, opts *FrameClickOptions) error

Click clicks an element matching provided selector.

func (*Page) Close

func (p *Page) Close(_ goja.Value) error

Close closes the page.

func (*Page) Content

func (p *Page) Content() string

Content returns the HTML content of the page.

func (*Page) Context

func (p *Page) Context() *BrowserContext

Context closes the page.

func (*Page) Dblclick

func (p *Page) Dblclick(selector string, opts goja.Value)

Dblclick double clicks an element matching provided selector.

func (*Page) DispatchEvent

func (p *Page) DispatchEvent(selector string, typ string, eventInit any, opts *FrameDispatchEventOptions) error

DispatchEvent dispatches an event on the page to the element that matches the provided selector.

func (*Page) EmulateMedia

func (p *Page) EmulateMedia(opts goja.Value)

func (*Page) EmulateVisionDeficiency

func (p *Page) EmulateVisionDeficiency(typ string)

EmulateVisionDeficiency activates/deactivates emulation of a vision deficiency.

func (*Page) Evaluate

func (p *Page) Evaluate(pageFunc string, args ...any) any

Evaluate runs JS code within the execution context of the main frame of the page.

func (*Page) EvaluateHandle

func (p *Page) EvaluateHandle(pageFunc string, args ...any) (JSHandleAPI, error)

EvaluateHandle runs JS code within the execution context of the main frame of the page.

func (*Page) Fill

func (p *Page) Fill(selector string, value string, opts goja.Value)

func (*Page) Focus

func (p *Page) Focus(selector string, opts goja.Value)

func (*Page) Frames

func (p *Page) Frames() []*Frame

Frames returns a list of frames on the page.

func (*Page) GetAttribute

func (p *Page) GetAttribute(selector string, name string, opts goja.Value) any

GetAttribute returns the attribute value of the element matching the provided selector.

func (*Page) GetKeyboard added in v0.8.1

func (p *Page) GetKeyboard() *Keyboard

GetKeyboard returns the keyboard for the page.

func (*Page) GetMouse added in v0.8.1

func (p *Page) GetMouse() *Mouse

GetMouse returns the mouse for the page.

func (*Page) GetTouchscreen added in v0.8.1

func (p *Page) GetTouchscreen() *Touchscreen

GetTouchscreen returns the touchscreen for the page.

func (*Page) Goto

func (p *Page) Goto(url string, opts *FrameGotoOptions) (*Response, error)

Goto will navigate the page to the specified URL and return a HTTP response object.

func (*Page) Hover

func (p *Page) Hover(selector string, opts goja.Value)

func (*Page) InnerHTML

func (p *Page) InnerHTML(selector string, opts goja.Value) string

func (*Page) InnerText

func (p *Page) InnerText(selector string, opts goja.Value) string

func (*Page) InputValue

func (p *Page) InputValue(selector string, opts goja.Value) string

func (*Page) IsChecked

func (p *Page) IsChecked(selector string, opts goja.Value) bool

IsChecked returns true if the first element that matches the selector is checked. Otherwise, returns false.

func (*Page) IsClosed

func (p *Page) IsClosed() bool

func (*Page) IsDisabled

func (p *Page) IsDisabled(selector string, opts goja.Value) bool

func (*Page) IsEditable

func (p *Page) IsEditable(selector string, opts goja.Value) bool

func (*Page) IsEnabled

func (p *Page) IsEnabled(selector string, opts goja.Value) bool

func (*Page) IsHidden

func (p *Page) IsHidden(selector string, opts goja.Value) (bool, error)

IsHidden will look for an element in the dom with given selector and see if the element is hidden. It will not wait for a match to occur. If no elements match `false` will be returned.

func (*Page) IsVisible

func (p *Page) IsVisible(selector string, opts goja.Value) (bool, error)

IsVisible will look for an element in the dom with given selector. It will not wait for a match to occur. If no elements match `false` will be returned.

func (*Page) Locator added in v0.4.0

func (p *Page) Locator(selector string, opts goja.Value) *Locator

Locator creates and returns a new locator for this page (main frame).

func (*Page) MainFrame

func (p *Page) MainFrame() *Frame

MainFrame returns the main frame on the page.

func (*Page) NavigationTimeout added in v1.4.0

func (p *Page) NavigationTimeout() time.Duration

NavigationTimeout returns the page's navigation timeout. It's an internal method not to be exposed as a JS API.

func (*Page) On added in v1.1.0

func (p *Page) On(event string, handler func(*ConsoleMessage)) error

On subscribes to a page event for which the given handler will be executed passing in the ConsoleMessage associated with the event. The only accepted event value is 'console'.

func (*Page) Opener

func (p *Page) Opener() *Page

Opener returns the opener of the target.

func (*Page) Press

func (p *Page) Press(selector string, key string, opts goja.Value)

func (*Page) Query

func (p *Page) Query(selector string) (*ElementHandle, error)

Query returns the first element matching the specified selector.

func (*Page) QueryAll

func (p *Page) QueryAll(selector string) ([]*ElementHandle, error)

QueryAll returns all elements matching the specified selector.

func (*Page) Referrer added in v1.4.0

func (p *Page) Referrer() string

Referrer returns the page's referrer. It's an internal method not to be exposed as a JS API.

func (*Page) Reload

func (p *Page) Reload(opts goja.Value) (*Response, error)

Reload will reload the current page.

func (*Page) Screenshot

func (p *Page) Screenshot(opts *PageScreenshotOptions, sp ScreenshotPersister) ([]byte, error)

Screenshot will instruct Chrome to save a screenshot of the current page and save it to specified file.

func (*Page) SelectOption

func (p *Page) SelectOption(selector string, values goja.Value, opts goja.Value) []string

func (*Page) SetContent

func (p *Page) SetContent(html string, opts goja.Value)

func (*Page) SetDefaultNavigationTimeout

func (p *Page) SetDefaultNavigationTimeout(timeout int64)

SetDefaultNavigationTimeout sets the default navigation timeout in milliseconds.

func (*Page) SetDefaultTimeout

func (p *Page) SetDefaultTimeout(timeout int64)

SetDefaultTimeout sets the default maximum timeout in milliseconds.

func (*Page) SetExtraHTTPHeaders

func (p *Page) SetExtraHTTPHeaders(headers map[string]string)

SetExtraHTTPHeaders sets default HTTP headers for page and whole frame hierarchy.

func (*Page) SetInputFiles

func (p *Page) SetInputFiles(selector string, files goja.Value, opts goja.Value) error

SetInputFiles sets input files for the selected element.

func (*Page) SetViewportSize

func (p *Page) SetViewportSize(viewportSize goja.Value)

SetViewportSize will update the viewport width and height.

func (*Page) Tap

func (p *Page) Tap(selector string, opts *FrameTapOptions) error

Tap will tap the element matching the provided selector.

func (*Page) TargetID added in v1.2.0

func (p *Page) TargetID() string

TargetID retrieve the unique id that is associated to this page. For internal use only.

func (*Page) TextContent

func (p *Page) TextContent(selector string, opts goja.Value) string

func (*Page) ThrottleCPU added in v1.2.0

func (p *Page) ThrottleCPU(cpuProfile CPUProfile) error

ThrottleCPU will slow the CPU down from chrome's perspective to simulate a test being run on a slower device.

func (*Page) ThrottleNetwork added in v1.2.0

func (p *Page) ThrottleNetwork(networkProfile NetworkProfile) error

ThrottleNetwork will slow the network down to simulate a slow network e.g. simulating a slow 3G connection.

func (*Page) Timeout added in v1.4.0

func (p *Page) Timeout() time.Duration

Timeout will return the default timeout or the one set by the user. It's an internal method not to be exposed as a JS API.

func (*Page) Title

func (p *Page) Title() string

func (*Page) Type

func (p *Page) Type(selector string, text string, opts goja.Value)

func (*Page) URL

func (p *Page) URL() string

URL returns the location of the page.

func (*Page) Uncheck

func (p *Page) Uncheck(selector string, opts goja.Value)

Uncheck unchecks an element matching the provided selector.

func (*Page) ViewportSize

func (p *Page) ViewportSize() map[string]float64

ViewportSize will return information on the viewport width and height.

func (*Page) WaitForFunction

func (p *Page) WaitForFunction(js string, opts *FrameWaitForFunctionOptions, jsArgs ...any) (any, error)

WaitForFunction waits for the given predicate to return a truthy value.

func (*Page) WaitForLoadState

func (p *Page) WaitForLoadState(state string, opts goja.Value)

WaitForLoadState waits for the specified page life cycle event.

func (*Page) WaitForNavigation

func (p *Page) WaitForNavigation(opts *FrameWaitForNavigationOptions) (*Response, error)

WaitForNavigation waits for the given navigation lifecycle event to happen.

func (*Page) WaitForSelector

func (p *Page) WaitForSelector(selector string, opts goja.Value) (*ElementHandle, error)

WaitForSelector waits for the given selector to match the waiting criteria.

func (*Page) WaitForTimeout

func (p *Page) WaitForTimeout(timeout int64)

WaitForTimeout waits the specified number of milliseconds.

func (*Page) Workers

func (p *Page) Workers() []*Worker

Workers returns all WebWorkers of page.

type PageEmulateMediaOptions

type PageEmulateMediaOptions struct {
	ColorScheme   ColorScheme   `json:"colorScheme"`
	Media         MediaType     `json:"media"`
	ReducedMotion ReducedMotion `json:"reducedMotion"`
}

func NewPageEmulateMediaOptions

func NewPageEmulateMediaOptions(defaultMedia MediaType, defaultColorScheme ColorScheme, defaultReducedMotion ReducedMotion) *PageEmulateMediaOptions

func (*PageEmulateMediaOptions) Parse

func (o *PageEmulateMediaOptions) Parse(ctx context.Context, opts goja.Value) error

type PageReloadOptions

type PageReloadOptions struct {
	WaitUntil LifecycleEvent `json:"waitUntil" js:"waitUntil"`
	Timeout   time.Duration  `json:"timeout"`
}

func NewPageReloadOptions

func NewPageReloadOptions(defaultWaitUntil LifecycleEvent, defaultTimeout time.Duration) *PageReloadOptions

func (*PageReloadOptions) Parse

func (o *PageReloadOptions) Parse(ctx context.Context, opts goja.Value) error

type PageScreenshotOptions

type PageScreenshotOptions struct {
	Clip           *page.Viewport `json:"clip"`
	Path           string         `json:"path"`
	Format         ImageFormat    `json:"format"`
	FullPage       bool           `json:"fullPage"`
	OmitBackground bool           `json:"omitBackground"`
	Quality        int64          `json:"quality"`
}

func NewPageScreenshotOptions

func NewPageScreenshotOptions() *PageScreenshotOptions

func (*PageScreenshotOptions) Parse

func (o *PageScreenshotOptions) Parse(ctx context.Context, opts goja.Value) error

type PollingType

type PollingType int

PollingType is the type of polling to use.

const (
	// PollingRaf is the requestAnimationFrame polling type.
	PollingRaf PollingType = iota

	// PollingMutation is the mutation polling type.
	PollingMutation

	// PollingInterval is the interval polling type.
	PollingInterval
)

func (PollingType) MarshalJSON

func (p PollingType) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted JSON string.

func (PollingType) String

func (p PollingType) String() string

func (*PollingType) UnmarshalJSON

func (p *PollingType) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a quoted JSON string to the enum value.

type Position

type Position struct {
	X float64 `json:"x"`
	Y float64 `json:"y"`
}

Position represents a position.

type Rect

type Rect struct {
	X      float64 `js:"x"`
	Y      float64 `js:"y"`
	Width  float64 `js:"width"`
	Height float64 `js:"height"`
}

Rect represents a rectangle.

type ReducedMotion

type ReducedMotion string

ReducedMotion represents a browser reduce-motion setting.

const (
	ReducedMotionReduce       ReducedMotion = "reduce"
	ReducedMotionNoPreference ReducedMotion = "no-preference"
)

Valid reduce-motion options.

func (ReducedMotion) MarshalJSON

func (r ReducedMotion) MarshalJSON() ([]byte, error)

MarshalJSON marshals the enum as a quoted JSON string.

func (ReducedMotion) String

func (r ReducedMotion) String() string

func (*ReducedMotion) UnmarshalJSON

func (r *ReducedMotion) UnmarshalJSON(b []byte) error

UnmarshalJSON unmarshals a quoted JSON string to the enum value.

type RemoteAddress

type RemoteAddress struct {
	IPAddress string `json:"ipAddress"`
	Port      int64  `json:"port"`
}

RemoteAddress contains informationa about a remote target.

type Request

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

Request represents a browser HTTP request.

func NewRequest

func NewRequest(ctx context.Context, rp NewRequestParams) (*Request, error)

NewRequest creates a new HTTP request.

func (*Request) AllHeaders

func (r *Request) AllHeaders() map[string]string

AllHeaders returns all the request headers.

func (*Request) Frame

func (r *Request) Frame() *Frame

Frame returns the frame within which the request was made.

func (*Request) HeaderValue

func (r *Request) HeaderValue(name string) goja.Value

HeaderValue returns the value of the given header.

func (*Request) Headers

func (r *Request) Headers() map[string]string

Headers returns the request headers.

func (*Request) HeadersArray

func (r *Request) HeadersArray() []HTTPHeader

HeadersArray returns the request headers as an array of objects.

func (*Request) IsNavigationRequest

func (r *Request) IsNavigationRequest() bool

IsNavigationRequest returns whether this was a navigation request or not.

func (*Request) Method

func (r *Request) Method() string

Method returns the request method.

func (*Request) PostData

func (r *Request) PostData() string

PostData returns the request post data, if any.

func (*Request) PostDataBuffer

func (r *Request) PostDataBuffer() goja.ArrayBuffer

PostDataBuffer returns the request post data as an ArrayBuffer.

func (*Request) ResourceType

func (r *Request) ResourceType() string

ResourceType returns the request resource type.

func (*Request) Response

func (r *Request) Response() *Response

Response returns the response for the request, if received.

func (*Request) Size

func (r *Request) Size() HTTPMessageSize

Size returns the size of the request.

func (*Request) Timing

func (r *Request) Timing() goja.Value

Timing returns the request timing information.

func (*Request) URL

func (r *Request) URL() string

URL returns the request URL.

type Response

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

Response represents a browser HTTP response.

func NewHTTPResponse

func NewHTTPResponse(
	ctx context.Context, req *Request, resp *network.Response, timestamp *cdp.MonotonicTime,
) *Response

NewHTTPResponse creates a new HTTP response.

func (*Response) AllHeaders

func (r *Response) AllHeaders() map[string]string

AllHeaders returns all the response headers.

func (*Response) Body

func (r *Response) Body() goja.ArrayBuffer

Body returns the response body as a binary buffer.

func (*Response) Frame

func (r *Response) Frame() *Frame

Frame returns the frame within which the response was received.

func (*Response) FromCache

func (r *Response) FromCache() bool

FromCache returns whether this response was served from disk cache.

func (*Response) FromPrefetchCache

func (r *Response) FromPrefetchCache() bool

FromPrefetchCache returns whether this response was served from prefetch cache.

func (*Response) FromServiceWorker

func (r *Response) FromServiceWorker() bool

FromServiceWorker returns whether this response was served by a service worker.

func (*Response) HeaderValue

func (r *Response) HeaderValue(name string) goja.Value

HeaderValue returns the value of the given header.

func (*Response) HeaderValues

func (r *Response) HeaderValues(name string) []string

HeaderValues returns the values of the given header.

func (*Response) Headers

func (r *Response) Headers() map[string]string

Headers returns the response headers.

func (*Response) HeadersArray

func (r *Response) HeadersArray() []HTTPHeader

HeadersArray returns the response headers as an array of objects.

func (*Response) JSON

func (r *Response) JSON() goja.Value

JSON returns the response body as JSON data.

func (*Response) Ok

func (r *Response) Ok() bool

Ok returns true if status code of response if considered ok, otherwise returns false.

func (*Response) Request

func (r *Response) Request() *Request

Request returns the request that led to this response.

func (*Response) SecurityDetails

func (r *Response) SecurityDetails() goja.Value

SecurityDetails returns the security details of the response.

func (*Response) ServerAddr

func (r *Response) ServerAddr() goja.Value

ServerAddr returns the remote address of the server.

func (*Response) Size

func (r *Response) Size() HTTPMessageSize

Size returns the size in bytes of the response.

func (*Response) Status

func (r *Response) Status() int64

Status returns the response status code.

func (*Response) StatusText

func (r *Response) StatusText() string

StatusText returns the response status text.

func (*Response) Text

func (r *Response) Text() string

Text returns the response body as a string.

func (*Response) URL

func (r *Response) URL() string

URL returns the request URL.

type Screen

type Screen struct {
	Width  int64 `js:"width"`
	Height int64 `js:"height"`
}

Screen represents a device screen.

func (*Screen) Parse

func (s *Screen) Parse(ctx context.Context, screen goja.Value) error

Parse parses the given screen options.

type ScreenshotPersister added in v1.4.0

type ScreenshotPersister interface {
	Persist(ctx context.Context, path string, data io.Reader) (err error)
}

ScreenshotPersister is the type that all file persisters must implement. It's job is to persist a file somewhere, hiding the details of where and how from the caller.

type ScrollIntoViewOptions added in v0.3.0

type ScrollIntoViewOptions struct {
	// Block defines vertical alignment.
	// One of start, center, end, or nearest.
	// Defaults to start.
	Block ScrollPosition `json:"block"`

	// Inline defines horizontal alignment.
	// One of start, center, end, or nearest.
	// Defaults to nearest.
	Inline ScrollPosition `json:"inline"`
}

ScrollIntoViewOptions change the behavior of ScrollIntoView. See: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

type ScrollPosition added in v0.3.0

type ScrollPosition string

ScrollPosition is a parameter for scrolling an element.

const (
	// ScrollPositionStart scrolls an element at the top of its parent.
	ScrollPositionStart ScrollPosition = "start"
	// ScrollPositionCenter scrolls an element at the center of its parent.
	ScrollPositionCenter ScrollPosition = "center"
	// ScrollPositionEnd scrolls an element at the end of its parent.
	ScrollPositionEnd ScrollPosition = "end"
	// ScrollPositionNearest scrolls an element at the nearest position of its parent.
	ScrollPositionNearest ScrollPosition = "nearest"
)

type SecurityDetails

type SecurityDetails struct {
	SubjectName string   `json:"subjectName"`
	Issuer      string   `json:"issuer"`
	ValidFrom   int64    `json:"validFrom"`
	ValidTo     int64    `json:"validTo"`
	Protocol    string   `json:"protocol"`
	SANList     []string `json:"sanList"`
}

SecurityDetails contains informationa about the security details of a TLS connection.

type SelectOption

type SelectOption struct {
	Value *string `json:"value"`
	Label *string `json:"label"`
	Index *int64  `json:"index"`
}

SelectOption represents a select option.

type Selector

type Selector struct {
	Selector string          `json:"selector"`
	Parts    []*SelectorPart `json:"parts"`

	// By default chained queries resolve to elements matched by the last selector,
	// but a selector can be prefixed with `*` to capture elements resolved by
	// an intermediate selector.
	Capture *int `json:"capture"`
}

func NewSelector

func NewSelector(selector string) (*Selector, error)

type SelectorPart

type SelectorPart struct {
	Name string `json:"name"`
	Body string `json:"body"`
}

type Session

type Session struct {
	BaseEventEmitter
	// contains filtered or unexported fields
}

Session represents a CDP session to a target.

func NewSession

func NewSession(
	ctx context.Context, conn *Connection, id target.SessionID, tid target.ID, logger *log.Logger, msgIDGen msgIDGenerator,
) *Session

NewSession creates a new session.

func (*Session) Closed added in v0.9.0

func (s *Session) Closed() bool

Closed returns true if this session is closed.

func (*Session) Done added in v0.3.0

func (s *Session) Done() <-chan struct{}

Done returns a channel that is closed when this session is closed.

func (*Session) Execute

func (s *Session) Execute(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error

Execute implements the cdp.Executor interface.

func (*Session) ExecuteWithoutExpectationOnReply

func (s *Session) ExecuteWithoutExpectationOnReply(ctx context.Context, method string, params easyjson.Marshaler, res easyjson.Unmarshaler) error

func (*Session) ID added in v0.2.0

func (s *Session) ID() target.SessionID

ID returns session ID.

func (*Session) TargetID added in v0.3.0

func (s *Session) TargetID() target.ID

TargetID returns session's target ID.

type Size

type Size struct {
	Width  float64 `js:"width"`
	Height float64 `js:"height"`
}

Size represents a size.

func (*Size) Parse

func (s *Size) Parse(ctx context.Context, viewport goja.Value) error

Parse size details from a given goja viewport value.

func (Size) String added in v0.4.0

func (s Size) String() string

type TimeoutSettings

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

TimeoutSettings holds information on timeout settings.

func NewTimeoutSettings

func NewTimeoutSettings(parent *TimeoutSettings) *TimeoutSettings

NewTimeoutSettings creates a new timeout settings object.

type Touchscreen

type Touchscreen struct {
	BaseEventEmitter
	// contains filtered or unexported fields
}

Touchscreen represents a touchscreen.

func NewTouchscreen

func NewTouchscreen(ctx context.Context, s session, k *Keyboard) *Touchscreen

NewTouchscreen returns a new TouchScreen.

func (*Touchscreen) Tap

func (t *Touchscreen) Tap(x float64, y float64) error

Tap dispatches a tap start and tap end event.

type Tracer added in v1.3.0

type Tracer interface {
	TraceAPICall(
		ctx context.Context, targetID string, spanName string, opts ...trace.SpanStartOption,
	) (context.Context, trace.Span)
	TraceNavigation(
		ctx context.Context, targetID string, opts ...trace.SpanStartOption,
	) (context.Context, trace.Span)
	TraceEvent(
		ctx context.Context, targetID string, eventName string, spanID string, opts ...trace.SpanStartOption,
	) (context.Context, trace.Span)
}

Tracer defines the interface with the tracing methods used in the common package.

func GetTracer added in v1.3.0

func GetTracer(ctx context.Context) Tracer

GetTracer returns the tracer attached to the context, or nil if not found.

type UnserializableValueError

type UnserializableValueError struct {
	UnserializableValue runtime.UnserializableValue
}

func (UnserializableValueError) Error

func (e UnserializableValueError) Error() string

Error satisfies the builtin error interface.

type Viewport

type Viewport struct {
	Width  int64 `js:"width"`
	Height int64 `js:"height"`
}

Viewport represents a page viewport.

func (*Viewport) Parse

func (v *Viewport) Parse(ctx context.Context, viewport goja.Value) error

Parse viewport details from a given goja viewport value.

func (Viewport) String added in v0.4.0

func (v Viewport) String() string

type WaitForEventOptions added in v1.2.0

type WaitForEventOptions struct {
	Timeout     time.Duration
	PredicateFn goja.Callable
}

WaitForEventOptions are the options used by the browserContext.waitForEvent API.

func NewWaitForEventOptions added in v1.2.0

func NewWaitForEventOptions(defaultTimeout time.Duration) *WaitForEventOptions

NewWaitForEventOptions created a new instance of WaitForEventOptions with a default timeout.

func (*WaitForEventOptions) Parse added in v1.2.0

func (w *WaitForEventOptions) Parse(ctx context.Context, optsOrPredicate goja.Value) error

Parse will parse the options or a callable predicate function. It can parse only a callable predicate function or an object which contains a callable predicate function and a timeout.

type Worker

type Worker struct {
	BaseEventEmitter
	// contains filtered or unexported fields
}

func NewWorker

func NewWorker(ctx context.Context, s session, id target.ID, url string) (*Worker, error)

NewWorker creates a new page viewport.

func (*Worker) URL

func (w *Worker) URL() string

URL returns the URL of the web worker.

Directories

Path Synopsis
Package js provides JavaScript code that the browser module evaluates on the browser.
Package js provides JavaScript code that the browser module evaluates on the browser.

Jump to

Keyboard shortcuts

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