playwright

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 20 Imported by: 0

README

goaneco-playwright

Go library for test automation with Microsoft Playwright. Write UI and API tests in Go using the same tool, running against Chromium, Firefox, and WebKit.

This project is open source, released under the MIT License. It was built primarily for personal use, but ideas, suggestions, and improvements are welcome — contributions that make the project more useful are always considered. You are also free to fork it and take it in whatever direction you like.


What can I test with this?

Test type Description Included example
UI / E2E Automates a real browser: clicks, forms, navigation, screenshots SauceDemo — 10 scenarios
API REST Sends HTTP requests (GET, POST, PUT, DELETE) and validates JSON responses — no browser needed Petstore API — 30 scenarios

Setup

1. Install the prerequisites
Tool Min version How to install
Go 1.21 Download and install from go.dev
Node.js 18 Download and install from nodejs.org
Playwright — npm install -g playwright
2. Install the browsers
npx playwright install chromium

On Linux, also install the OS-level dependencies:

npx playwright install --with-deps chromium
3. Set the environment variable

All tests need to know where the Playwright CLI is located:

# Linux / macOS
export PLAYWRIGHT_CLI_PATH=$(npm root -g)/playwright/node_modules/playwright-core/cli.js

# Windows PowerShell
$env:PLAYWRIGHT_CLI_PATH = "$env:APPDATA\npm\node_modules\playwright\node_modules\playwright-core\cli.js"

Add this line to your shell profile (~/.bashrc, ~/.zshrc, etc.) so you don't have to repeat it every session.


What tests look like

Tests are organized as scenarios — one file per test case. Each test is a Go function that clearly describes what it is verifying.

UI test (with Page Object Model)

Target: https://www.saucedemo.com — a demo e-commerce site used for UI automation practice.

func TestLoginAndInventory(t *testing.T) {
    must := require.New(t)
    is   := assert.New(t)
    page := newPage(t)           // opens a new browser tab
    loginStandardUser(t, page)   // helper that logs in with standard credentials

    ctx := testCtx(t)
    inv := pom.NewInventoryPage(page)

    count, err := inv.ProductCount(ctx)
    must.NoError(err)
    is.Equal(6, count)   // the inventory must show exactly 6 products
}

The Page Object Model (POM) wraps the actions of each screen into a reusable struct (pom.InventoryPage, pom.CartPage, etc.), keeping tests clean and easy to read.

API test (full lifecycle)

Target: https://petstore.swagger.io/v2 — a public REST API used as a sandbox for API automation practice.

func TestScenario12PetFullLifecycle(t *testing.T) {
    must := require.New(t)
    is   := assert.New(t)
    ctx    := testCtx(t)
    apiCtx := newAPICtx(t)   // HTTP client pointed at the API base URL

    // Create a pet
    pet := &models.Pet{Name: "LifecyclePet", PhotoURLs: []string{"https://example.com/img.jpg"}, Status: "available"}
    postResp, err := apiCtx.Post(ctx, "/pet", &playwright.APIFetchOptions{
        Headers: jsonHeaders(),
        Data:    mustJSON(t, pet),
    })
    must.NoError(err)
    defer postResp.Dispose(ctx)
    must.Equal(200, postResp.Status())
    postBody, err := postResp.Body(ctx)
    must.NoError(err)
    created := mustUnmarshalPet(t, postBody)
    must.Greater(created.ID, int64(0))

    // Verify it can be retrieved
    getResp, err := apiCtx.Get(ctx, fmt.Sprintf("/pet/%d", created.ID))
    must.NoError(err)
    defer getResp.Dispose(ctx)
    is.Equal(200, getResp.Status())

    // Update the status to "sold"
    created.Status = "sold"
    putResp, err := apiCtx.Put(ctx, "/pet", &playwright.APIFetchOptions{Headers: jsonHeaders(), Data: mustJSON(t, created)})
    must.NoError(err)
    defer putResp.Dispose(ctx)
    is.Equal(200, putResp.Status())

    // Delete the pet
    delResp, err := apiCtx.Delete(ctx, fmt.Sprintf("/pet/%d", created.ID))
    must.NoError(err)
    defer delResp.Dispose(ctx)
    is.Equal(200, delResp.Status())

    // Confirm it no longer exists (404)
    confirmResp, err := apiCtx.Get(ctx, fmt.Sprintf("/pet/%d", created.ID))
    must.NoError(err)
    defer confirmResp.Dispose(ctx)
    is.Equal(404, confirmResp.Status())
}

Included examples

UI automation — SauceDemo (examples/ui-automation/)

Browser automation for SauceDemo using the Page Object Model pattern. The 10 scenarios cover the complete flow of an online store.

# Run all scenarios
PLAYWRIGHT_CLI_PATH="..." go test -tags e2e -v -timeout 300s ./examples/ui-automation/...

# Run a single scenario
PLAYWRIGHT_CLI_PATH="..." go test -tags e2e -v -timeout 120s -run TestFullCheckoutFlow ./examples/ui-automation/...
# Scenario What it verifies
01 Login and inventory Authentication smoke test; confirms 6 products are visible
02 Add items to cart Adds 3 products; verifies cart badge count and item list
03 Sort by price low to high The cheapest item (Onesie, $7.99) appears first
04 Sort by name Z to A Products are listed in reverse alphabetical order
05 Full checkout flow Add → cart → fill info → overview → order confirmation
06 Remove item from cart Adds 3 items, removes 1, confirms 2 remain
07 Product detail page Verifies name, price, and description of a product
08 Logout via burger menu Opens side nav, clicks Logout, confirms login screen
09 Add most expensive item Sorts high to low; adds Fleece Jacket ($49.99) to cart
10 Footer social links Verifies visible Twitter, Facebook, and LinkedIn links

Screens are abstracted as Page Objects in examples/ui-automation/pom/:

Page Object Available actions
LoginPage Navigate, Login, IsVisible, ErrorMessage
InventoryPage ProductCount, AddToCart, CartBadgeCount, Sort, Logout
CartPage ItemCount, GetItemNames, GetItemPrices, RemoveItem, Checkout
CheckoutInfoPage FillInfo, Continue, ErrorMessage
CheckoutOverviewPage GetItemCount, GetSubtotal, GetTotal, Finish
CheckoutCompletePage GetHeader, BackHome
ProductDetailPage GetName, GetPrice, GetDescription, AddToCart, BackToInventory

Full scenario descriptions: examples/ui-automation/ui-automation.md


API automation — Petstore (examples/api-automation/)

30 test scenarios against the public Petstore API. No browser is launched — only HTTP requests and response assertions.

# Run all scenarios
PLAYWRIGHT_CLI_PATH="..." go test -tags e2e -v -timeout 300s ./examples/api-automation/...

# Run a single scenario
PLAYWRIGHT_CLI_PATH="..." go test -tags e2e -v -timeout 60s -run TestScenario01AddPet ./examples/api-automation/...
Pet — /pet endpoints (01–12)
# Scenario Endpoint Verifies
01 Add a pet POST /pet id > 0, name and status match
02 Get by ID GET /pet/{id} Returned fields match created pet
03 Update a pet PUT /pet Status updated to "sold"
04 Delete a pet DELETE /pet/{id} Subsequent GET returns 404
05–07 Find by status GET /pet/findByStatus Table-driven: available / pending / sold
08 Find by multiple statuses GET /pet/findByStatus?status=available&status=pending Only those two statuses in response
09 Update with form data POST /pet/{id} (form-encoded) Status 200
10 Find by tag GET /pet/findByTags?tags=goaneco Valid JSON array
11 Non-existent pet GET /pet/999999999 Status 404
12 Full lifecycle POST → GET → PUT → DELETE → GET Final GET returns 404
Store — /store endpoints (13–20)
# Scenario Endpoint Verifies
13 Get inventory GET /store/inventory Non-empty status-count map
14 Place an order POST /store/order id > 0, status == "placed"
15 Get order by ID GET /store/order/{id} Fields match placed order
16 Delete an order DELETE /store/order/{id} Subsequent GET returns 404
17 Place completed order POST /store/order (complete: true) complete == true in response
18 Non-existent order GET /store/order/999999 Status 404
19 Order with quantity POST /store/order (quantity: 5) quantity == 5 in response
20 Full order lifecycle POST → GET → DELETE → GET Final GET returns 404
Users — /user endpoints (21–30)
# Scenario Endpoint Verifies
21 Create a user POST /user + GET /user/{username} Fields match
22 Get by username GET /user/{username} username matches
23 Update a user PUT /user/{username} + GET Updated email returned
24 Delete a user DELETE /user/{username} Subsequent GET returns 404
25 Login with valid credentials GET /user/login Status 200, token present in body
26 Logout GET /user/logout Status 200
27 Create users with array POST /user/createWithArray Each user retrievable via GET
28 Create users with list POST /user/createWithList Each user retrievable via GET
29 Login with invalid credentials GET /user/login (bad credentials) Response is not 2xx
30 Full user lifecycle POST → login → GET → PUT → DELETE → GET Final GET returns 404

Full scenario descriptions: examples/api-automation/api-automation.md


Running against multiple browsers

UI tests can run on Chromium (default), Firefox, or WebKit:

# Firefox
PLAYWRIGHT_CLI_PATH="..." PLAYWRIGHT_BROWSER=firefox go test -tags e2e -v -timeout 300s ./examples/ui-automation/...

# WebKit (Safari engine)
PLAYWRIGHT_CLI_PATH="..." PLAYWRIGHT_BROWSER=webkit go test -tags e2e -v -timeout 300s ./examples/ui-automation/...

Test coverage

This library is validated by 3,318 tests spread across three layers:

Layer Tests What it covers
Library E2E suite (e2e/) 3,278 Core Playwright capabilities: browser, page, locator, frames, network, API requests, assertions, tracing, screenshots, and more — 124 test files covering the full API surface
UI automation examples (examples/ui-automation/) 10 End-to-end browser flows on SauceDemo using the Page Object Model pattern
API automation examples (examples/api-automation/) 30 REST API scenarios against the public Petstore API — no browser required

The library E2E suite was built using playwright-java as a reference, porting and adapting its test cases to Go to ensure equivalent behavior coverage.


License

MIT License — see LICENSE for details.

Go Reference Go Report Card

Documentation

Overview

Package playwright provides a Go client for Microsoft Playwright.

Playwright enables reliable end-to-end testing and browser automation across Chromium, Firefox, and WebKit using a modern async IPC architecture.

API Stability Notice: This package is currently in active development (pre-v1.0 / experimental). Public APIs, method signatures, and structures may undergo refinement prior to the first stable v1.0.0 release. Breaking changes across experimental versions will be documented in release notes.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIFetchOptions

type APIFetchOptions struct {
	Method           *string
	Headers          map[string]string
	Data             []byte
	Params           map[string]string
	FormData         []FormDataField  // application/x-www-form-urlencoded fields
	MultipartData    []MultipartField // multipart/form-data fields
	MaxRedirects     *int
	MaxRetries       *int
	FailOnStatusCode *bool
	Timeout          *float64
}

APIFetchOptions configures a single fetch request.

type APIRequestContext

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

APIRequestContext enables making HTTP requests outside a browser page, useful for API testing and setup/teardown operations.

func (*APIRequestContext) Delete

func (c *APIRequestContext) Delete(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Delete makes a DELETE request to the given URL.

func (*APIRequestContext) Dispose

func (c *APIRequestContext) Dispose(ctx context.Context, reason ...string) error

Dispose releases all resources associated with this request context. An optional reason string is included in subsequent-call error messages.

func (*APIRequestContext) Fetch

func (c *APIRequestContext) Fetch(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Fetch makes an HTTP request and returns the response.

func (*APIRequestContext) Get

func (c *APIRequestContext) Get(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Get makes a GET request to the given URL.

func (*APIRequestContext) Head

func (c *APIRequestContext) Head(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Head makes a HEAD request to the given URL.

func (*APIRequestContext) Patch

func (c *APIRequestContext) Patch(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Patch makes a PATCH request to the given URL.

func (*APIRequestContext) Post

func (c *APIRequestContext) Post(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Post makes a POST request to the given URL.

func (*APIRequestContext) Put

func (c *APIRequestContext) Put(ctx context.Context, url string, opts ...*APIFetchOptions) (*APIResponse, error)

Put makes a PUT request to the given URL.

func (*APIRequestContext) StorageState

func (c *APIRequestContext) StorageState(ctx context.Context) (*StorageState, error)

StorageState returns the current cookies stored in this request context.

type APIRequestContextOptions

type APIRequestContextOptions struct {
	BaseURL           *string
	ExtraHTTPHeaders  map[string]string
	HttpCredentials   *HttpCredentials
	UserAgent         *string
	IgnoreHTTPSErrors *bool
	Timeout           *float64
	MaxRedirects      *int
	FailOnStatusCode  *bool
}

APIRequestContextOptions configures a new APIRequestContext.

type APIResponse

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

APIResponse represents an HTTP response received by APIRequestContext.

func (*APIResponse) Body

func (r *APIResponse) Body(ctx context.Context) ([]byte, error)

Body returns the response body as bytes.

func (*APIResponse) Dispose

func (r *APIResponse) Dispose(ctx context.Context) error

Dispose releases the response body resources on the Playwright server.

func (*APIResponse) Headers

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

Headers returns response headers as a name→value map.

func (*APIResponse) JSON

func (r *APIResponse) JSON(ctx context.Context) (any, error)

JSON parses the response body as JSON and returns the result.

func (*APIResponse) OK

func (r *APIResponse) OK() bool

OK returns true if the status code is in the 200-299 range.

func (*APIResponse) SecurityDetails

func (r *APIResponse) SecurityDetails() *protocol.SecurityDetails

SecurityDetails returns TLS certificate details for HTTPS responses, or nil for HTTP.

func (*APIResponse) ServerAddr

func (r *APIResponse) ServerAddr() *protocol.RemoteAddr

ServerAddr returns the remote address of the server that served the response, or nil if the information is not available.

func (*APIResponse) Status

func (r *APIResponse) Status() int

Status returns the HTTP status code.

func (*APIResponse) StatusText

func (r *APIResponse) StatusText() string

StatusText returns the HTTP status text.

func (*APIResponse) Text

func (r *APIResponse) Text(ctx context.Context) (string, error)

Text returns the response body as a UTF-8 string.

func (*APIResponse) Timing

func (r *APIResponse) Timing() *APIResponseTiming

Timing returns network timing information for the request, or nil if unavailable.

func (*APIResponse) URL

func (r *APIResponse) URL() string

URL returns the response URL.

type APIResponseAssertions

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

APIResponseAssertions provides assertion methods for an APIResponse.

func ExpectAPIResponse

func ExpectAPIResponse(response *APIResponse) *APIResponseAssertions

ExpectAPIResponse creates a new APIResponseAssertions for the given response.

func (*APIResponseAssertions) Not

Not returns a negated version of the assertion.

func (*APIResponseAssertions) ToBeOK

func (a *APIResponseAssertions) ToBeOK(ctx context.Context) error

ToBeOK asserts that the response status is in the 200-299 range.

type APIResponseTiming

type APIResponseTiming struct {
	StartTime             float64
	DomainLookupStart     float64
	DomainLookupEnd       float64
	ConnectStart          float64
	SecureConnectionStart float64
	ConnectEnd            float64
	RequestStart          float64
	ResponseStart         float64
	ResponseEnd           float64
}

APIResponseTiming holds network timing metrics for an APIResponse.

type AddLocatorHandlerOptions

type AddLocatorHandlerOptions struct {
	// NoWaitAfter disables waiting for the handler's locator to become hidden after
	// the handler returns. Useful when the handler itself waits for the element to hide.
	NoWaitAfter *bool
	// Times limits how many times the handler is invoked. After Times calls the
	// handler is automatically unregistered. Zero or nil means unlimited.
	Times *int
}

AddLocatorHandlerOptions configures the behavior of AddLocatorHandler.

type AriaRole

type AriaRole string

AriaRole represents an ARIA role for use with GetByRole.

const (
	AriaRoleAlert            AriaRole = "alert"
	AriaRoleAlertDialog      AriaRole = "alertdialog"
	AriaRoleApplication      AriaRole = "application"
	AriaRoleArticle          AriaRole = "article"
	AriaRoleBanner           AriaRole = "banner"
	AriaRoleBlockquote       AriaRole = "blockquote"
	AriaRoleButton           AriaRole = "button"
	AriaRoleCaption          AriaRole = "caption"
	AriaRoleCell             AriaRole = "cell"
	AriaRoleCheckbox         AriaRole = "checkbox"
	AriaRoleCode             AriaRole = "code"
	AriaRoleColumnHeader     AriaRole = "columnheader"
	AriaRoleCombobox         AriaRole = "combobox"
	AriaRoleComplementary    AriaRole = "complementary"
	AriaRoleContentInfo      AriaRole = "contentinfo"
	AriaRoleDefinition       AriaRole = "definition"
	AriaRoleDeletion         AriaRole = "deletion"
	AriaRoleDialog           AriaRole = "dialog"
	AriaRoleDirectory        AriaRole = "directory"
	AriaRoleDocument         AriaRole = "document"
	AriaRoleEmphasis         AriaRole = "emphasis"
	AriaRoleFeed             AriaRole = "feed"
	AriaRoleFigure           AriaRole = "figure"
	AriaRoleForm             AriaRole = "form"
	AriaRoleGeneric          AriaRole = "generic"
	AriaRoleGrid             AriaRole = "grid"
	AriaRoleGridCell         AriaRole = "gridcell"
	AriaRoleGroup            AriaRole = "group"
	AriaRoleHeading          AriaRole = "heading"
	AriaRoleImg              AriaRole = "img"
	AriaRoleInsertion        AriaRole = "insertion"
	AriaRoleLink             AriaRole = "link"
	AriaRoleList             AriaRole = "list"
	AriaRoleListBox          AriaRole = "listbox"
	AriaRoleListItem         AriaRole = "listitem"
	AriaRoleLog              AriaRole = "log"
	AriaRoleMain             AriaRole = "main"
	AriaRoleMarquee          AriaRole = "marquee"
	AriaRoleMath             AriaRole = "math"
	AriaRoleMenu             AriaRole = "menu"
	AriaRoleMenuBar          AriaRole = "menubar"
	AriaRoleMenuItem         AriaRole = "menuitem"
	AriaRoleMenuItemCheckbox AriaRole = "menuitemcheckbox"
	AriaRoleMenuItemRadio    AriaRole = "menuitemradio"
	AriaRoleMeter            AriaRole = "meter"
	AriaRoleNavigation       AriaRole = "navigation"
	AriaRoleNone             AriaRole = "none"
	AriaRoleNote             AriaRole = "note"
	AriaRoleOption           AriaRole = "option"
	AriaRoleParagraph        AriaRole = "paragraph"
	AriaRolePresentation     AriaRole = "presentation"
	AriaRoleProgressBar      AriaRole = "progressbar"
	AriaRoleRadio            AriaRole = "radio"
	AriaRoleRadioGroup       AriaRole = "radiogroup"
	AriaRoleRegion           AriaRole = "region"
	AriaRoleRow              AriaRole = "row"
	AriaRoleRowGroup         AriaRole = "rowgroup"
	AriaRoleRowHeader        AriaRole = "rowheader"
	AriaRoleScrollBar        AriaRole = "scrollbar"
	AriaRoleSearch           AriaRole = "search"
	AriaRoleSearchBox        AriaRole = "searchbox"
	AriaRoleSeparator        AriaRole = "separator"
	AriaRoleSlider           AriaRole = "slider"
	AriaRoleSpinButton       AriaRole = "spinbutton"
	AriaRoleStatus           AriaRole = "status"
	AriaRoleStrong           AriaRole = "strong"
	AriaRoleSubscript        AriaRole = "subscript"
	AriaRoleSuperscript      AriaRole = "superscript"
	AriaRoleSwitch           AriaRole = "switch"
	AriaRoleTab              AriaRole = "tab"
	AriaRoleTable            AriaRole = "table"
	AriaRoleTabList          AriaRole = "tablist"
	AriaRoleTabPanel         AriaRole = "tabpanel"
	AriaRoleTerm             AriaRole = "term"
	AriaRoleTextbox          AriaRole = "textbox"
	AriaRoleTime             AriaRole = "time"
	AriaRoleTimer            AriaRole = "timer"
	AriaRoleToolBar          AriaRole = "toolbar"
	AriaRoleToolTip          AriaRole = "tooltip"
	AriaRoleTree             AriaRole = "tree"
	AriaRoleTreeGrid         AriaRole = "treegrid"
	AriaRoleTreeItem         AriaRole = "treeitem"
)

type BindingHandler

type BindingHandler func(args ...any) any

BindingHandler is called when JavaScript invokes an exposed binding. args contains the deserialized JavaScript arguments. The return value is serialized and sent back to JavaScript.

type BoundingBox

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

BoundingBox represents the bounding rectangle of an element on screen.

type Browser

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

Browser represents a local or remote browser instance.

func (*Browser) BrowserType

func (b *Browser) BrowserType() *BrowserType

BrowserType returns the BrowserType that launched this browser. Returns nil if the Browser was created through a mechanism other than Launch.

func (*Browser) Close

func (b *Browser) Close(ctx context.Context) error

Close terminates the browser and all associated browser contexts. It is idempotent: later calls perform no action and return nil.

Fail-fast design: local state (connected = false, contexts = nil) is updated immediately to prevent redundant concurrent calls. If the underlying IPC call fails due to driver disconnection, the Playwright server automatically cleans up remote resources on process termination.

func (*Browser) Contexts

func (b *Browser) Contexts() []*BrowserContext

Contexts returns a slice of all active BrowserContext instances belonging to this Browser.

func (*Browser) IsConnected

func (b *Browser) IsConnected() bool

IsConnected returns true if the browser is actively connected to the Playwright driver.

func (*Browser) NewContext

func (b *Browser) NewContext(ctx context.Context, options ...*BrowserContextOptions) (*BrowserContext, error)

NewContext creates a new isolated browser context. Accepts optional BrowserContextOptions for configuring viewport, userAgent, locale, geolocation, etc.

func (*Browser) NewPage

func (b *Browser) NewPage(ctx context.Context, options ...*BrowserContextOptions) (*Page, error)

NewPage is a convenience method that creates a new browser context and then a new page. If page creation fails, the context is closed to prevent leaks on the server.

func (*Browser) OnContext

func (b *Browser) OnContext(fn func(*BrowserContext)) func()

OnContext registers a callback that is invoked whenever a new BrowserContext is created in this browser. The returned function unregisters the handler; calling it more than once is safe.

func (*Browser) Version

func (b *Browser) Version() string

Version returns the browser version. The value comes from the protocol initializer sent in the __create__ event.

type BrowserContext

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

BrowserContext represents an isolated browser session (equivalent to an incognito profile).

func (*BrowserContext) AddCookies

func (c *BrowserContext) AddCookies(ctx context.Context, cookies []Cookie) error

AddCookies adds cookies to this browser context.

func (*BrowserContext) AddInitScript

func (b *BrowserContext) AddInitScript(ctx context.Context, script string) error

AddInitScript injects a JavaScript script that runs before any page script on every navigation in all pages of this context.

func (*BrowserContext) Browser

func (c *BrowserContext) Browser() *Browser

Browser returns the Browser instance to which this context belongs.

func (*BrowserContext) ClearCookies

func (c *BrowserContext) ClearCookies(ctx context.Context, options ...*ClearCookiesOptions) error

ClearCookies clears cookies from the context, optionally filtered by name, domain, or path.

func (*BrowserContext) ClearPermissions

func (c *BrowserContext) ClearPermissions(ctx context.Context) error

ClearPermissions resets all permission overrides for this context.

func (*BrowserContext) Clock

func (c *BrowserContext) Clock() *Clock

Clock returns a Clock instance for this browser context.

func (*BrowserContext) Close

func (c *BrowserContext) Close(ctx context.Context) error

Close closes the browser context and all its associated pages. It is idempotent: later calls perform no action and return nil.

Fail-fast design: local state (closed = true, pages = nil) is updated immediately to prevent redundant concurrent calls. If the underlying IPC call fails due to driver disconnection, the Playwright server automatically cleans up remote resources on process termination.

func (*BrowserContext) Cookies

func (c *BrowserContext) Cookies(ctx context.Context, urls ...string) ([]Cookie, error)

Cookies returns cookies matching specified URLs or all cookies in context if URLs are omitted.

func (*BrowserContext) Credentials

func (c *BrowserContext) Credentials() *Credentials

Credentials returns the Credentials object for this BrowserContext. The Credentials GUID comes from the BrowserContext initializer.

func (*BrowserContext) Debugger

func (c *BrowserContext) Debugger() *Debugger

Debugger returns the Debugger object for this BrowserContext. The Debugger GUID comes from the BrowserContext initializer.

func (*BrowserContext) ExposeBinding

func (c *BrowserContext) ExposeBinding(ctx context.Context, name string, handler BindingHandler) error

ExposeBinding exposes a Go function as a global JavaScript function in all pages of this context. When JavaScript calls window[name](...args), handler is invoked with the deserialized args. Returns an error if the IPC registration fails. Re-registering the same name replaces the handler.

func (*BrowserContext) GrantPermissions

func (c *BrowserContext) GrantPermissions(ctx context.Context, permissions []string, origin ...string) error

GrantPermissions grants browser permissions to the given origin. Pass no origin to grant permissions to all origins.

func (*BrowserContext) IsClosed

func (c *BrowserContext) IsClosed() bool

IsClosed returns true if the context has been closed.

func (*BrowserContext) NewCDPSession

func (c *BrowserContext) NewCDPSession(ctx context.Context, page *Page) (*CDPSession, error)

NewCDPSession creates a new CDP session for the given page (Chromium only).

func (*BrowserContext) NewPage

func (c *BrowserContext) NewPage(ctx context.Context) (*Page, error)

NewPage creates a new page in this browser context. Resolves the mainFrame GUID from the page initializer, then loads the Frame initializer so the initial URL is immediately available without additional IPC calls.

func (*BrowserContext) OnConsole

func (c *BrowserContext) OnConsole(handler func(*ConsoleMessage)) func()

OnConsole registers a handler for all console messages in this context, regardless of which page emitted them. Unlike Page.OnConsole, this handler fires for messages from popups and other pages within the same context. The returned function cancels the listener.

func (*BrowserContext) OnPage

func (c *BrowserContext) OnPage(fn func(*Page)) func()

OnPage registers a handler that fires whenever a new page is created in this context, including popup pages opened via window.open(). The returned function unregisters the handler.

func (*BrowserContext) OnPageClose

func (c *BrowserContext) OnPageClose(fn func(*Page)) func()

OnPageClose registers a handler that fires when any page in this context closes. Returns a function that cancels the registration.

func (*BrowserContext) OnPageLoad

func (c *BrowserContext) OnPageLoad(fn func(*Page)) func()

OnPageLoad registers a handler that fires when any page in this context reaches "load" state. Returns a function that cancels the registration.

func (*BrowserContext) OnRequest

func (c *BrowserContext) OnRequest(handler func(*NetworkRequest)) func()

OnRequest registers a handler that fires for every network request in this context. The returned function cancels the listener; it is idempotent (safe to call multiple times).

func (*BrowserContext) OnRequestFailed

func (c *BrowserContext) OnRequestFailed(handler func(*NetworkRequest)) func()

OnRequestFailed registers a handler that fires when a network request fails. The returned function cancels the listener; it is idempotent (safe to call multiple times).

func (*BrowserContext) OnRequestFinished

func (c *BrowserContext) OnRequestFinished(handler func(*NetworkRequest)) func()

OnRequestFinished registers a handler that fires when a network request completes. The returned function cancels the listener; it is idempotent (safe to call multiple times).

func (*BrowserContext) OnResponse

func (c *BrowserContext) OnResponse(handler func(*NetworkResponse)) func()

OnResponse registers a handler that fires for every network response in this context. The returned function cancels the listener; it is idempotent (safe to call multiple times).

func (*BrowserContext) Pages

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

Pages returns a slice containing all active pages in this BrowserContext.

func (*BrowserContext) RegisterSelectorEngine

func (b *BrowserContext) RegisterSelectorEngine(
	ctx context.Context,
	name string,
	script string,
	opts ...*RegisterSelectorEngineOptions,
) error

RegisterSelectorEngine registers a custom selector engine for use within this BrowserContext. name is the selector engine name (only [a-zA-Z0-9_] characters are allowed). script is a JavaScript string that evaluates to a selector engine object with create, query, and queryAll methods.

func (*BrowserContext) Request

func (c *BrowserContext) Request() *APIRequestContext

Request returns the APIRequestContext bound to this BrowserContext. Requests made through it share cookies and credentials with pages in the context.

func (*BrowserContext) Route

func (c *BrowserContext) Route(ctx context.Context, pattern string, handler RouteHandler, opts ...*BrowserContextRouteOptions) error

Route registers a network interception handler for all pages in this context. Multiple calls stack handlers in LIFO order; a handler may call Route.Fallback to defer to the next registered handler.

func (*BrowserContext) RouteFromHAR

func (c *BrowserContext) RouteFromHAR(ctx context.Context, harPath string, opts ...*RouteFromHAROptions) error

RouteFromHAR reads a HAR file and serves matching requests from its recorded responses. Requests that do not match any HAR entry are passed through to the network.

func (*BrowserContext) SetExtraHTTPHeaders

func (c *BrowserContext) SetExtraHTTPHeaders(ctx context.Context, headers map[string]string) error

SetExtraHTTPHeaders sets extra HTTP headers to be sent with every request in this context. Calling with an empty map removes all previously set extra headers.

func (*BrowserContext) SetGeolocation

func (c *BrowserContext) SetGeolocation(ctx context.Context, geo *Geolocation) error

SetGeolocation sets the geolocation for this context. Pass nil to clear any previously set geolocation.

func (*BrowserContext) SetOffline

func (c *BrowserContext) SetOffline(ctx context.Context, offline bool) error

SetOffline toggles offline mode for the entire context.

func (*BrowserContext) SetTestIdAttribute

func (c *BrowserContext) SetTestIdAttribute(ctx context.Context, attributeName string) error

SetTestIdAttribute changes the attribute name used by GetByTestId locators. The default is "data-testid". Calling this in a @AfterEach/cleanup resets it.

func (*BrowserContext) StorageState

func (c *BrowserContext) StorageState(ctx context.Context) (*StorageState, error)

StorageState returns a snapshot of the current cookies and localStorage for this context.

func (*BrowserContext) TestIdAttributeName added in v1.0.3

func (c *BrowserContext) TestIdAttributeName() string

TestIdAttributeName returns the attribute name used by GetByTestId locators. Defaults to "data-testid" if SetTestIdAttribute has not been called.

func (*BrowserContext) Tracing

func (c *BrowserContext) Tracing() *Tracing

Tracing returns the Tracing object for this BrowserContext. The Tracing GUID comes from the BrowserContext initializer.

func (*BrowserContext) Unroute

func (c *BrowserContext) Unroute(ctx context.Context) error

Unroute removes all network interception patterns from this context and deregisters the route event listener.

func (*BrowserContext) WaitForEvent

func (c *BrowserContext) WaitForEvent(ctx context.Context, event string) (any, error)

WaitForEvent waits for a context-level event to fire and returns its payload. Supported events: "page" (*Page), "request" (*NetworkRequest), "response" (*NetworkResponse).

type BrowserContextOptions

type BrowserContextOptions struct {
	AcceptDownloads   *bool               `json:"acceptDownloads,omitempty"`
	BaseURL           *string             `json:"baseURL,omitempty"`
	BypassCSP         *bool               `json:"bypassCSP,omitempty"`
	ColorScheme       *string             `json:"colorScheme,omitempty"`
	DeviceScaleFactor *float64            `json:"deviceScaleFactor,omitempty"`
	ExtraHTTPHeaders  map[string]string   `json:"extraHTTPHeaders,omitempty"`
	ForcedColors      *string             `json:"forcedColors,omitempty"`
	Geolocation       *Geolocation        `json:"geolocation,omitempty"`
	HasTouch          *bool               `json:"hasTouch,omitempty"`
	HttpCredentials   *HttpCredentials    `json:"httpCredentials,omitempty"`
	IgnoreHTTPSErrors *bool               `json:"ignoreHTTPSErrors,omitempty"`
	IsMobile          *bool               `json:"isMobile,omitempty"`
	JavaScriptEnabled *bool               `json:"javaScriptEnabled,omitempty"`
	Locale            *string             `json:"locale,omitempty"`
	NoDefaultViewport *bool               `json:"noDefaultViewport,omitempty"`
	Offline           *bool               `json:"offline,omitempty"`
	Permissions       []string            `json:"permissions,omitempty"`
	Proxy             *ProxyOptions       `json:"proxy,omitempty"`
	ReducedMotion     *string             `json:"reducedMotion,omitempty"`
	Screen            *ScreenSize         `json:"screen,omitempty"`
	RecordVideo       *RecordVideoOptions `json:"-"`                        // client-side: passed to wire params separately
	ServiceWorkers    *string             `json:"serviceWorkers,omitempty"` // "allow" | "block"
	StorageState      *StorageState       `json:"storageState,omitempty"`
	StorageStatePath  *string             `json:"-"` // client-side: path to a JSON file containing StorageState
	StrictSelectors   *bool               `json:"strictSelectors,omitempty"`
	TimezoneID        *string             `json:"timezoneId,omitempty"`
	UserAgent         *string             `json:"userAgent,omitempty"`
	Viewport          *ViewportSize       `json:"viewport,omitempty"`
}

BrowserContextOptions provides complete configuration settings for Browser.NewContext.

type BrowserContextRouteOptions

type BrowserContextRouteOptions struct {
	// Times limits how many times the handler is invoked. After Times calls the
	// handler is automatically skipped (subsequent requests go through normally).
	Times *int
}

BrowserContextRouteOptions specifies optional parameters for BrowserContext.Route.

type BrowserType

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

BrowserType provides methods to launch and connect to browser instances.

func (*BrowserType) ConnectOverCDP

func (b *BrowserType) ConnectOverCDP(
	ctx context.Context,
	endpointURL string,
	opts ...*ConnectOverCDPOptions,
) (*Browser, error)

ConnectOverCDP connects to an existing browser instance over the Chrome DevTools Protocol. endpointURL is the CDP WebSocket endpoint URL (e.g. "http://localhost:9222/").

func (*BrowserType) ExecutablePath

func (b *BrowserType) ExecutablePath() string

ExecutablePath returns the path to the browser executable binary. The value originates from the protocol initializer.

func (*BrowserType) Launch

func (b *BrowserType) Launch(ctx context.Context, opts ...*BrowserTypeLaunchOptions) (*Browser, error)

Launch launches a new browser instance using this BrowserType. Options can be omitted to use default settings, or a pointer to BrowserTypeLaunchOptions to customize launching (headless, args, slowMo, timeout, channel, executablePath, etc.).

func (*BrowserType) LaunchPersistentContext

func (b *BrowserType) LaunchPersistentContext(ctx context.Context, userDataDir string, opts ...*LaunchPersistentContextOptions) (*Browser, *BrowserContext, error)

LaunchPersistentContext launches a browser instance with a persistent user profile stored at userDataDir. Returns a Browser and its associated BrowserContext.

func (*BrowserType) Name

func (b *BrowserType) Name() string

Name returns the browser name (e.g. "chromium", "firefox", "webkit"). The value originates from the protocol initializer.

type BrowserTypeLaunchOptions

type BrowserTypeLaunchOptions struct {
	Args            []string          `json:"args,omitempty"`
	Channel         *string           `json:"channel,omitempty"`
	ChromiumSandbox *bool             `json:"chromiumSandbox,omitempty"`
	Devtools        *bool             `json:"devtools,omitempty"`
	DownloadsPath   *string           `json:"downloadsPath,omitempty"`
	Env             map[string]string `json:"env,omitempty"`
	ExecutablePath  *string           `json:"executablePath,omitempty"`
	// FirefoxUserPrefs is Firefox-only. json:"-" prevents accidental JSON serialization of this
	// public field; it is copied into the internal wire struct (firefoxUserPrefs) during Launch.
	FirefoxUserPrefs map[string]any `json:"-"`
	HandleSIGHUP     *bool          `json:"handleSIGHUP,omitempty"`
	HandleSIGINT     *bool          `json:"handleSIGINT,omitempty"`
	HandleSIGTERM    *bool          `json:"handleSIGTERM,omitempty"`
	Headless         *bool          `json:"headless,omitempty"`
	SlowMo           *float64       `json:"slowMo,omitempty"`
	Timeout          *float64       `json:"timeout,omitempty"`
	TracesDir        *string        `json:"tracesDir,omitempty"`
}

BrowserTypeLaunchOptions provides complete configuration settings for BrowserType.Launch.

type CDPSession

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

CDPSession provides a raw Chrome DevTools Protocol (CDP) session for direct protocol communication with Chromium.

func (*CDPSession) Detach

func (s *CDPSession) Detach(ctx context.Context) error

Detach detaches the CDPSession from the target.

func (*CDPSession) On

func (s *CDPSession) On(method string, handler func(json.RawMessage)) func()

On registers a handler for CDP events with the given method name. The handler receives the raw event parameters as JSON. The returned function cancels the listener.

func (*CDPSession) OnClose

func (s *CDPSession) OnClose(handler func()) connection.ListenerID

OnClose registers a one-time handler called when the CDPSession is closed. The returned ListenerID can be used to cancel the listener.

func (*CDPSession) Send

func (s *CDPSession) Send(ctx context.Context, method string, params any) (json.RawMessage, error)

Send sends a CDP command and returns the result. Method is the CDP domain and method name (e.g. "Runtime.evaluate"). Params are the command parameters (or nil for no params).

type ChannelOwner

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

ChannelOwner is the base struct embedded by all remote Playwright protocol objects. It provides generic IPC routing capabilities.

func (*ChannelOwner) GUID

func (c *ChannelOwner) GUID() string

GUID returns the unique identifier of the remote object.

func (*ChannelOwner) Initializer

func (c *ChannelOwner) Initializer(guid string) json.RawMessage

Initializer returns the raw JSON initializer for the given GUID from the connection.

func (*ChannelOwner) SendMessageRequest

func (c *ChannelOwner) SendMessageRequest(ctx context.Context, method string, params any) (json.RawMessage, error)

SendMessageRequest wraps an IPC request to the underlying connection, serializing the given parameters and waiting for the response. Returns json.RawMessage containing valid JSON ready for unmarshaling.

type ClearCookiesOptions

type ClearCookiesOptions struct {
	Name      *string        `json:"name,omitempty"`
	NameRegex *regexp.Regexp `json:"-"`
	Domain    *string        `json:"domain,omitempty"`
	Path      *string        `json:"path,omitempty"`
}

ClearCookiesOptions configures optional filters for clearing cookies.

type Clock

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

Clock provides control over the browser context's fake clock, enabling tests to manipulate time-dependent logic without waiting for real time to pass. Obtained via BrowserContext.Clock().

func (*Clock) FastForward

func (c *Clock) FastForward(ctx context.Context, ms float64) error

FastForward advances the fake clock by the given number of milliseconds, firing all timers that expire during that period without blocking.

func (*Clock) Install

func (c *Clock) Install(ctx context.Context, timeMs ...float64) error

Install replaces the native browser clock with a fake one. timeMs is the initial time in milliseconds since the Unix epoch; omit or pass 0 to use the current real time.

func (*Clock) PauseAt

func (c *Clock) PauseAt(ctx context.Context, timeMs float64) error

PauseAt pauses the fake clock at the given time (milliseconds since epoch). No timers fire until Resume is called.

func (*Clock) Resume

func (c *Clock) Resume(ctx context.Context) error

Resume resumes a previously paused clock, allowing timers to fire normally.

func (*Clock) RunFor

func (c *Clock) RunFor(ctx context.Context, ms float64) error

RunFor simulates the passage of time by the given milliseconds, running all timers that fire during that period.

func (*Clock) SetFixedTime

func (c *Clock) SetFixedTime(ctx context.Context, timeMs float64) error

SetFixedTime fixes both Date.now() and new Date() to return the given time (milliseconds since epoch) without installing a fake clock for timers.

func (*Clock) SetSystemTime

func (c *Clock) SetSystemTime(ctx context.Context, timeMs float64) error

SetSystemTime changes the system clock value to the given time (milliseconds since epoch) without changing how timers fire.

type ConnectOverCDPOptions

type ConnectOverCDPOptions struct {
	// Headers is a map of additional HTTP headers sent with the WebSocket handshake.
	Headers map[string]string
	// SlowMo slows down Playwright operations by the specified amount of milliseconds.
	SlowMo *float64
}

ConnectOverCDPOptions specifies optional parameters for BrowserType.ConnectOverCDP.

type ConsoleMessage

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

ConsoleMessage represents a message logged to the browser console.

func (*ConsoleMessage) Location

func (m *ConsoleMessage) Location() string

Location returns the source location of the message as "url:line:column".

func (*ConsoleMessage) Text

func (m *ConsoleMessage) Text() string

Text returns the concatenated text of all console arguments.

func (*ConsoleMessage) Timestamp

func (m *ConsoleMessage) Timestamp() float64

Timestamp returns the timestamp of the message in milliseconds since the Unix epoch.

func (*ConsoleMessage) Type

func (m *ConsoleMessage) Type() string

Type returns the log level: "log", "error", "warn", "info", "debug", etc.

type Cookie struct {
	Name     string            `json:"name"`
	Value    string            `json:"value"`
	URL      *string           `json:"url,omitempty"`
	Domain   *string           `json:"domain,omitempty"`
	Path     *string           `json:"path,omitempty"`
	Expires  *float64          `json:"expires,omitempty"`
	HTTPOnly *bool             `json:"httpOnly,omitempty"`
	Secure   *bool             `json:"secure,omitempty"`
	SameSite SameSiteAttribute `json:"sameSite,omitempty"`
}

Cookie represents a cookie in the storage state or browser context.

type Credentials

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

Credentials provides a virtual WebAuthn authenticator scoped to a BrowserContext. Obtain via BrowserContext.Credentials().

func (*Credentials) Create

Create registers a new virtual credential for the given relying party ID.

func (*Credentials) Delete

func (cr *Credentials) Delete(ctx context.Context, id string) error

Delete removes the virtual credential with the given ID.

func (*Credentials) Get

Get returns virtual credentials matching the given filter options.

func (*Credentials) Install

func (cr *Credentials) Install(ctx context.Context) error

Install activates the virtual authenticator for this browser context. After calling Install, WebAuthn operations use the virtual authenticator instead of the platform authenticator.

type CredentialsCreateOptions

type CredentialsCreateOptions struct {
	// ID is the credential identifier (base64url-encoded). If empty, the server generates one.
	ID *string
	// UserHandle is the user handle (base64url-encoded).
	UserHandle *string
	// PrivateKey is the private key in PKCS#8 PEM format.
	PrivateKey *string
	// PublicKey is the public key in SPKI PEM format.
	PublicKey *string
}

CredentialsCreateOptions configures Credentials.Create.

type CredentialsGetOptions

type CredentialsGetOptions struct {
	// RpID filters credentials to those registered for this relying party ID.
	RpID *string
	// ID filters to a single credential by its ID.
	ID *string
}

CredentialsGetOptions filters the credentials returned by Credentials.Get.

type Debugger

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

Debugger provides step-through debugging for a BrowserContext. Obtain via BrowserContext.Debugger().

func (*Debugger) Next

func (d *Debugger) Next(ctx context.Context) error

Next advances one step when paused.

func (*Debugger) OnPausedStateChanged

func (d *Debugger) OnPausedStateChanged(handler func(*DebuggerPausedDetails)) func()

OnPausedStateChanged registers a handler called each time the debugger pause state changes. The handler receives the new paused details, or nil when execution is resumed. The returned function cancels the listener.

func (*Debugger) PausedDetails

func (d *Debugger) PausedDetails(ctx context.Context) (*DebuggerPausedDetails, error)

PausedDetails returns the current paused state details, or nil if not paused. This is a client-side read of the last received pausedStateChanged event. Use OnPausedStateChanged to track state changes asynchronously.

func (*Debugger) RequestPause

func (d *Debugger) RequestPause(ctx context.Context) error

RequestPause requests that execution pauses at the next Playwright action.

func (*Debugger) Resume

func (d *Debugger) Resume(ctx context.Context) error

Resume resumes execution after a pause.

func (*Debugger) RunTo

func (d *Debugger) RunTo(ctx context.Context, location DebuggerLocation) error

RunTo resumes execution until the given source location is reached.

type DebuggerLocation

type DebuggerLocation struct {
	File   string `json:"file"`
	Line   *int   `json:"line,omitempty"`
	Column *int   `json:"column,omitempty"`
}

DebuggerLocation identifies a source position (file + optional line/column).

type DebuggerPausedDetails

type DebuggerPausedDetails struct {
	Location *DebuggerLocation `json:"location,omitempty"`
	Title    string            `json:"title"`
	Stack    *string           `json:"stack,omitempty"`
}

DebuggerPausedDetails contains information about why execution is paused.

type Dialog

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

Dialog represents a browser dialog (alert, confirm, prompt, or beforeunload).

func (*Dialog) Accept

func (d *Dialog) Accept(ctx context.Context, promptText ...string) error

Accept accepts the dialog. For prompt dialogs, promptText sets the input value.

func (*Dialog) DefaultValue

func (d *Dialog) DefaultValue() string

DefaultValue returns the default value for prompt dialogs (empty for others).

func (*Dialog) Dismiss

func (d *Dialog) Dismiss(ctx context.Context) error

Dismiss dismisses the dialog (equivalent to clicking Cancel).

func (*Dialog) Message

func (d *Dialog) Message() string

Message returns the message shown in the dialog.

func (*Dialog) Type

func (d *Dialog) Type() string

Type returns the dialog type: "alert", "confirm", "prompt", or "beforeunload".

type Download

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

Download represents a file download started by the browser.

func (*Download) Cancel

func (d *Download) Cancel(ctx context.Context) error

Cancel cancels the in-progress download.

func (*Download) Delete

func (d *Download) Delete(ctx context.Context) error

Delete removes the downloaded file.

func (*Download) Failure

func (d *Download) Failure(ctx context.Context) error

Failure returns an error if the download failed, or nil if it succeeded.

func (*Download) Path

func (d *Download) Path(ctx context.Context) (string, error)

Path returns the path to the completed download file. Blocks until the download is finished.

func (*Download) SaveAs

func (d *Download) SaveAs(ctx context.Context, path string) error

SaveAs copies the downloaded file to the specified path.

func (*Download) SuggestedFilename

func (d *Download) SuggestedFilename() string

SuggestedFilename returns the browser-suggested filename for the download.

func (*Download) URL

func (d *Download) URL() string

URL returns the download URL.

type ElementHandle

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

ElementHandle represents a reference to a DOM element in the browser.

func (*ElementHandle) AsJSHandle

func (e *ElementHandle) AsJSHandle() *JSHandle

AsJSHandle returns this element handle as a JSHandle.

func (*ElementHandle) BoundingBox

func (e *ElementHandle) BoundingBox(ctx context.Context) (*BoundingBox, error)

BoundingBox returns the bounding box of the element, or nil if not visible.

func (*ElementHandle) Check

func (e *ElementHandle) Check(ctx context.Context) error

Check checks a checkbox or radio button element.

func (*ElementHandle) Click

func (e *ElementHandle) Click(ctx context.Context) error

Click performs a click on the element.

func (*ElementHandle) DblClick

func (e *ElementHandle) DblClick(ctx context.Context) error

DblClick performs a double-click on the element.

func (*ElementHandle) DispatchEvent

func (e *ElementHandle) DispatchEvent(ctx context.Context, eventType string, eventInit ...any) error

DispatchEvent dispatches an event of the given type on the element. eventInit can optionally provide event initialization data.

func (*ElementHandle) Dispose

func (e *ElementHandle) Dispose(ctx context.Context) error

Dispose releases the element handle from the browser.

func (*ElementHandle) Evaluate

func (e *ElementHandle) Evaluate(ctx context.Context, expression string, arg ...any) (any, error)

Evaluate executes a JavaScript expression with this element as the argument.

func (*ElementHandle) EvaluateHandle

func (e *ElementHandle) EvaluateHandle(ctx context.Context, expression string, arg ...any) (*JSHandle, error)

EvaluateHandle executes a JavaScript expression with this element as the argument and returns a JSHandle.

func (*ElementHandle) Fill

func (e *ElementHandle) Fill(ctx context.Context, value string) error

Fill sets the value of an input element.

func (*ElementHandle) Focus

func (e *ElementHandle) Focus(ctx context.Context) error

Focus gives focus to the element.

func (*ElementHandle) GetAttribute

func (e *ElementHandle) GetAttribute(ctx context.Context, name string) (*string, error)

GetAttribute returns the value of the named attribute, or nil if the attribute does not exist.

func (*ElementHandle) Hover

func (e *ElementHandle) Hover(ctx context.Context) error

Hover moves the mouse to the center of the element.

func (*ElementHandle) InnerHTML

func (e *ElementHandle) InnerHTML(ctx context.Context) (string, error)

InnerHTML returns the inner HTML of the element.

func (*ElementHandle) InnerText

func (e *ElementHandle) InnerText(ctx context.Context) (string, error)

InnerText returns the inner text of the element.

func (*ElementHandle) InputValue

func (e *ElementHandle) InputValue(ctx context.Context) (string, error)

InputValue returns the current value of an input, textarea, or select element.

func (*ElementHandle) IsChecked

func (e *ElementHandle) IsChecked(ctx context.Context) (bool, error)

IsChecked returns true if the element is checked.

func (*ElementHandle) IsDisabled

func (e *ElementHandle) IsDisabled(ctx context.Context) (bool, error)

IsDisabled returns true if the element is disabled.

func (*ElementHandle) IsEditable

func (e *ElementHandle) IsEditable(ctx context.Context) (bool, error)

IsEditable returns true if the element is editable.

func (*ElementHandle) IsEnabled

func (e *ElementHandle) IsEnabled(ctx context.Context) (bool, error)

IsEnabled returns true if the element is enabled.

func (*ElementHandle) IsHidden

func (e *ElementHandle) IsHidden(ctx context.Context) (bool, error)

IsHidden returns true if the element is hidden.

func (*ElementHandle) IsVisible

func (e *ElementHandle) IsVisible(ctx context.Context) (bool, error)

IsVisible returns true if the element is visible.

func (*ElementHandle) JSONValue

func (e *ElementHandle) JSONValue(ctx context.Context) (any, error)

JSONValue returns the JSON value of this element handle.

func (*ElementHandle) Press

func (e *ElementHandle) Press(ctx context.Context, key string) error

Press presses a key while the element is focused.

func (*ElementHandle) QuerySelector

func (e *ElementHandle) QuerySelector(ctx context.Context, selector string) (*ElementHandle, error)

QuerySelector returns the first child element matching the selector, or nil.

func (*ElementHandle) QuerySelectorAll

func (e *ElementHandle) QuerySelectorAll(ctx context.Context, selector string) ([]*ElementHandle, error)

QuerySelectorAll returns all child elements matching the selector.

func (*ElementHandle) Screenshot

func (e *ElementHandle) Screenshot(ctx context.Context, opts ...*ScreenshotOptions) ([]byte, error)

Screenshot captures a screenshot of this element. Returns raw PNG bytes by default; pass ScreenshotOptions to select JPEG or quality. If opts.Path is set, the image is also written to that file path.

func (*ElementHandle) ScrollIntoViewIfNeeded

func (e *ElementHandle) ScrollIntoViewIfNeeded(ctx context.Context) error

ScrollIntoViewIfNeeded scrolls the element into view if it is not already visible.

func (*ElementHandle) SelectOption

func (e *ElementHandle) SelectOption(ctx context.Context, values ...string) ([]string, error)

SelectOption selects options in a <select> element by value. Returns the list of selected option values.

func (*ElementHandle) SetChecked

func (e *ElementHandle) SetChecked(ctx context.Context, checked bool) error

SetChecked sets the checked state of the element.

func (*ElementHandle) Tap

func (e *ElementHandle) Tap(ctx context.Context) error

Tap taps the element (mobile-like gesture).

func (*ElementHandle) TextContent

func (e *ElementHandle) TextContent(ctx context.Context) (string, error)

TextContent returns the text content of the element and its descendants.

func (*ElementHandle) Type

func (e *ElementHandle) Type(ctx context.Context, text string) error

Type types text into the element, one character at a time.

func (*ElementHandle) Uncheck

func (e *ElementHandle) Uncheck(ctx context.Context) error

Uncheck unchecks a checkbox element.

func (*ElementHandle) WaitForElementState

func (e *ElementHandle) WaitForElementState(ctx context.Context, state string) error

WaitForElementState waits until the element reaches the given state. Valid states: "visible", "hidden", "stable", "enabled", "disabled", "editable".

type EmulateMediaOptions

type EmulateMediaOptions struct {
	// Media specifies the CSS media type: "screen", "print", or "null" to reset.
	Media *string
	// ColorScheme specifies the color scheme: "dark", "light", "no-preference", or "null" to reset.
	ColorScheme *string
	// ReducedMotion specifies the reduced motion preference: "reduce", "no-preference", or "null" to reset.
	ReducedMotion *string
	// ForcedColors specifies the forced colors mode: "active", "none", or "null" to reset.
	ForcedColors *string
	// Contrast specifies the contrast preference: "more", "no-preference", or "null" to reset.
	Contrast *string
}

EmulateMediaOptions contains options for Page.EmulateMedia.

type FileChooser

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

FileChooser represents a browser file chooser dialog opened when an <input type="file"> element is activated. Use SetFiles to supply the chosen files programmatically.

func (*FileChooser) IsMultiple

func (f *FileChooser) IsMultiple() bool

IsMultiple reports whether the file chooser accepts multiple files.

func (*FileChooser) Page

func (f *FileChooser) Page() *Page

Page returns the page that owns this file chooser.

func (*FileChooser) SetFiles

func (f *FileChooser) SetFiles(ctx context.Context, paths []string) error

SetFiles sets the chosen files by their local filesystem paths.

func (*FileChooser) SetFilesPayload

func (f *FileChooser) SetFilesPayload(ctx context.Context, payloads []FilePayload) error

SetFilesPayload sets the chosen files from in-memory payloads.

type FilePayload

type FilePayload struct {
	Name     string
	MimeType string
	Buffer   []byte
}

FilePayload represents an in-memory file for use with SetInputFilesPayload.

type FormDataField

type FormDataField struct {
	Name  string
	Value string
}

FormDataField is a single name-value pair for application/x-www-form-urlencoded requests.

type Frame

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

Frame represents an iframe or the main frame of a page. Methods mirror Page's navigation/evaluation API but are scoped to the frame.

func (*Frame) Content

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

Content returns the full HTML of the frame.

func (*Frame) Evaluate

func (f *Frame) Evaluate(ctx context.Context, expression string, arg ...any) (any, error)

Evaluate executes a JavaScript expression in the frame and returns the deserialized result.

func (*Frame) Goto

func (f *Frame) Goto(ctx context.Context, url string) error

Goto navigates the frame to the given URL.

func (*Frame) IsDetached

func (f *Frame) IsDetached() bool

IsDetached reports whether this frame has been detached from the page.

func (*Frame) Locator

func (f *Frame) Locator(selector string) *Locator

Locator returns a new Locator scoped to this frame.

func (*Frame) Name

func (f *Frame) Name() string

Name returns the frame's name attribute from the embedding element.

func (*Frame) Press

func (f *Frame) Press(ctx context.Context, selector, key string) error

Press presses a keyboard key while the element matching selector is focused.

func (*Frame) QuerySelector

func (f *Frame) QuerySelector(ctx context.Context, selector string) (*ElementHandle, error)

QuerySelector returns the first element matching the selector in this frame.

func (*Frame) SetContent

func (f *Frame) SetContent(ctx context.Context, html string) error

SetContent sets the HTML markup of the frame.

func (*Frame) Title

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

Title returns the document title of the frame.

func (*Frame) URL

func (f *Frame) URL() string

URL returns the frame's current URL.

func (*Frame) WaitForLoadState

func (f *Frame) WaitForLoadState(ctx context.Context, state ...string) error

WaitForLoadState waits until the frame reaches the given load state. Valid states: "load" (default), "domcontentloaded", "networkidle". Delegates to the server-side waitForLoadState IPC, which handles past lifecycle events and supports "networkidle" correctly.

type FrameLocator

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

FrameLocator represents an iframe element and allows locating elements inside it. All locator methods are scoped to the iframe's document.

func (*FrameLocator) FrameLocator

func (f *FrameLocator) FrameLocator(selector string) *FrameLocator

FrameLocator returns a nested FrameLocator for locating elements within an iframe inside this frame.

func (*FrameLocator) GetByLabel

func (f *FrameLocator) GetByLabel(text string, opts ...*GetByLabelOptions) *Locator

GetByLabel returns a Locator scoped to this frame matching form elements by associated label text.

func (*FrameLocator) GetByRole

func (f *FrameLocator) GetByRole(role AriaRole, opts ...*GetByRoleOptions) *Locator

GetByRole returns a Locator scoped to this frame matching elements by ARIA role.

func (*FrameLocator) GetByTestId

func (f *FrameLocator) GetByTestId(testId string) *Locator

GetByTestId returns a Locator scoped to this frame matching elements by the configured testid attribute. The attribute name defaults to "data-testid" and can be changed with BrowserContext.SetTestIdAttribute.

func (*FrameLocator) GetByText

func (f *FrameLocator) GetByText(text string, opts ...*GetByTextOptions) *Locator

GetByText returns a Locator scoped to this frame matching elements by visible text.

func (*FrameLocator) Locator

func (f *FrameLocator) Locator(selector string) *Locator

Locator returns a Locator scoped to this frame, matching elements by CSS/internal selector.

type Geolocation

type Geolocation struct {
	Latitude  float64  `json:"latitude"`
	Longitude float64  `json:"longitude"`
	Accuracy  *float64 `json:"accuracy,omitempty"`
}

Geolocation specifies geographical coordinates.

type GetByAltTextOptions

type GetByAltTextOptions struct {
	Exact *bool
}

GetByAltTextOptions contains optional filters for GetByAltText.

type GetByLabelOptions

type GetByLabelOptions struct {
	Exact *bool
}

GetByLabelOptions contains optional filters for GetByLabel.

type GetByPlaceholderOptions

type GetByPlaceholderOptions struct {
	Exact *bool
}

GetByPlaceholderOptions contains optional filters for GetByPlaceholder.

type GetByRoleOptions

type GetByRoleOptions struct {
	Name *string
	// Exact controls whether Name matching is case-sensitive and exact. Does not affect role matching.
	Exact         *bool
	Checked       *bool
	Disabled      *bool
	Pressed       *bool
	Selected      *bool
	Expanded      *bool
	Level         *int
	IncludeHidden *bool
}

GetByRoleOptions contains optional filters for GetByRole.

type GetByTextOptions

type GetByTextOptions struct {
	Exact *bool
}

GetByTextOptions contains optional filters for GetByText.

type GetByTitleOptions

type GetByTitleOptions struct {
	Exact *bool
}

GetByTitleOptions contains optional filters for GetByTitle.

type HttpCredentials

type HttpCredentials struct {
	Username string  `json:"username"`
	Password string  `json:"password"`
	Origin   *string `json:"origin,omitempty"`
	Send     *string `json:"send,omitempty"`
}

HttpCredentials represents HTTP basic/digest authentication credentials.

type JSHandle

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

JSHandle represents an in-page JavaScript object reference.

func (*JSHandle) Dispose

func (h *JSHandle) Dispose(ctx context.Context) error

Dispose releases the handle, freeing it in the browser process.

func (*JSHandle) Evaluate

func (h *JSHandle) Evaluate(ctx context.Context, expression string, arg ...any) (any, error)

Evaluate executes a JavaScript expression in the context of the handle and returns the result.

func (*JSHandle) EvaluateHandle

func (h *JSHandle) EvaluateHandle(ctx context.Context, expression string, arg ...any) (*JSHandle, error)

EvaluateHandle executes a JavaScript expression and returns the result as a JSHandle.

func (*JSHandle) GetProperty

func (h *JSHandle) GetProperty(ctx context.Context, name string) (*JSHandle, error)

GetProperty returns a JSHandle for the named property of the object.

func (*JSHandle) JSONValue

func (h *JSHandle) JSONValue(ctx context.Context) (any, error)

JSONValue returns the JSON-serializable value of the handle.

type Keyboard

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

Keyboard provides keyboard input methods for a page. Access via Page.Keyboard.

func (*Keyboard) Down

func (k *Keyboard) Down(ctx context.Context, key string) error

Down dispatches a keydown event for the given key.

func (*Keyboard) InsertText

func (k *Keyboard) InsertText(ctx context.Context, text string) error

InsertText dispatches an input event with the given text, bypassing key events.

func (*Keyboard) Press

func (k *Keyboard) Press(ctx context.Context, key string) error

Press presses a key and releases it (down + up). Supports modifier combos like "Shift+A".

func (*Keyboard) Type

func (k *Keyboard) Type(ctx context.Context, text string) error

Type types the given text by sending keydown, keypress/input, and keyup events for each character.

func (*Keyboard) Up

func (k *Keyboard) Up(ctx context.Context, key string) error

Up dispatches a keyup event for the given key.

type LaunchPersistentContextOptions

type LaunchPersistentContextOptions struct {
	// Launch options (subset of BrowserTypeLaunchOptions)
	Args             []string
	Channel          *string
	Headless         *bool
	SlowMo           *float64
	ExecutablePath   *string
	FirefoxUserPrefs map[string]any
	// Context options (subset of BrowserContextOptions)
	AcceptDownloads   *bool
	BaseURL           *string
	BypassCSP         *bool
	ColorScheme       *string
	Contrast          *string
	DeviceScaleFactor *float64
	ExtraHTTPHeaders  map[string]string
	ForcedColors      *string
	Geolocation       *Geolocation
	HasTouch          *bool
	HttpCredentials   *HttpCredentials
	IgnoreHTTPSErrors *bool
	IsMobile          *bool
	JavaScriptEnabled *bool
	Locale            *string
	Offline           *bool
	Permissions       []string
	ReducedMotion     *string
	TimezoneID        *string
	UserAgent         *string
	Viewport          *ViewportSize
}

LaunchPersistentContextOptions configures BrowserType.LaunchPersistentContext.

type LocalStorageEntry

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

LocalStorageEntry represents a key-value pair in localStorage.

type Locator

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

Locator provides a way to find and interact with elements on a page. Locator objects are strict: they enforce that exactly one element matches the selector when performing actions (unless Count is used).

func (*Locator) All

func (l *Locator) All(ctx context.Context) ([]*Locator, error)

All returns all elements matching this locator as a slice of individual Locators.

func (*Locator) AllInnerTexts

func (l *Locator) AllInnerTexts(ctx context.Context) ([]string, error)

AllInnerTexts returns the inner text of all elements matching this locator. Uses evalOnSelectorAll IPC to support compound selectors (e.g. "article >> p").

func (*Locator) AllTextContents

func (l *Locator) AllTextContents(ctx context.Context) ([]string, error)

AllTextContents returns the text content of all elements matching this locator. Uses evalOnSelectorAll IPC to support compound selectors (e.g. "article >> p").

func (*Locator) And

func (l *Locator) And(other *Locator) *Locator

And returns a new Locator that matches elements satisfying both this locator and the given locator simultaneously.

func (*Locator) AriaSnapshot

func (l *Locator) AriaSnapshot(ctx context.Context, opts ...*LocatorAriaSnapshotOptions) (string, error)

func (*Locator) BoundingBox

func (l *Locator) BoundingBox(ctx context.Context) (*BoundingBox, error)

BoundingBox returns the bounding box of the element matched by this locator, or nil if the element is not visible. Uses a two-step querySelector + ElementHandle call because the Playwright v1.61.1 wire protocol does not expose Frame.boundingBox directly.

func (*Locator) Check

func (l *Locator) Check(ctx context.Context) error

Check checks a checkbox or radio element.

func (*Locator) Clear

func (l *Locator) Clear(ctx context.Context) error

Clear clears the value of an editable element (input, textarea) matched by this locator.

func (*Locator) Click

func (l *Locator) Click(ctx context.Context, opts ...*LocatorClickOptions) error

Click clicks the element.

func (*Locator) Count

func (l *Locator) Count(ctx context.Context) (int, error)

Count returns the number of elements matching the locator's selector.

func (*Locator) DblClick

func (l *Locator) DblClick(ctx context.Context) error

DblClick performs a double-click on the matched element.

func (*Locator) DragTo

func (l *Locator) DragTo(ctx context.Context, target *Locator) error

AriaSnapshot returns the ARIA snapshot of the element matched by this locator. The snapshot is a YAML string representing the accessibility tree. DragTo performs a drag-and-drop from this locator's element to the target locator's element.

func (*Locator) Evaluate

func (l *Locator) Evaluate(ctx context.Context, expression string, arg ...any) (any, error)

Evaluate evaluates an expression on the first element matching this locator and returns the result.

func (*Locator) EvaluateAll

func (l *Locator) EvaluateAll(ctx context.Context, expression string, arg ...any) (any, error)

EvaluateAll evaluates an expression on all elements matching this locator and returns the result.

func (*Locator) Fill

func (l *Locator) Fill(ctx context.Context, value string) error

Fill sets the value of an input element.

func (*Locator) Filter

func (l *Locator) Filter(opts *LocatorFilterOptions) *Locator

Filter narrows the Locator to elements that satisfy the given filter options. Multiple options are applied cumulatively (AND semantics).

func (*Locator) First

func (l *Locator) First() *Locator

First returns a locator that narrows the match to the first matching element.

func (*Locator) Focus

func (l *Locator) Focus(ctx context.Context) error

Focus focuses the element matched by this locator.

func (*Locator) FrameLocator

func (l *Locator) FrameLocator(selector string) *FrameLocator

FrameLocator scopes subsequent locator lookups within the first iframe matching selector.

func (*Locator) GetAttribute

func (l *Locator) GetAttribute(ctx context.Context, name string) (*string, error)

GetAttribute returns the value of an attribute on the element. Returns nil if the attribute does not exist.

func (*Locator) Highlight

func (l *Locator) Highlight(ctx context.Context) error

Highlight visually highlights the element matched by this locator in the browser. Useful during debugging and authoring. The highlight is temporary and browser-internal.

func (*Locator) Hover

func (l *Locator) Hover(ctx context.Context) error

Hover moves the mouse pointer over the matched element.

func (*Locator) InnerHTML

func (l *Locator) InnerHTML(ctx context.Context) (string, error)

InnerHTML returns the element's inner HTML.

func (*Locator) InnerText

func (l *Locator) InnerText(ctx context.Context) (string, error)

InnerText returns the element's inner text.

func (*Locator) InputValue

func (l *Locator) InputValue(ctx context.Context) (string, error)

InputValue returns the value of an input, textarea, or select element.

func (*Locator) IsChecked

func (l *Locator) IsChecked(ctx context.Context) (bool, error)

IsChecked returns true if the element is checked (checkbox or radio button).

func (*Locator) IsDisabled

func (l *Locator) IsDisabled(ctx context.Context) (bool, error)

IsDisabled returns true if the element is disabled.

func (*Locator) IsEditable

func (l *Locator) IsEditable(ctx context.Context) (bool, error)

IsEditable returns true if the element is editable.

func (*Locator) IsEnabled

func (l *Locator) IsEnabled(ctx context.Context) (bool, error)

IsEnabled returns true if the element is enabled.

func (*Locator) IsVisible

func (l *Locator) IsVisible(ctx context.Context) (bool, error)

IsVisible returns true if the element is visible.

func (*Locator) Last

func (l *Locator) Last() *Locator

Last returns a locator that narrows the match to the last matching element.

func (*Locator) Locator

func (l *Locator) Locator(selector string) *Locator

Locator returns a new Locator scoped to descendants of this locator that match selector.

func (*Locator) Nth

func (l *Locator) Nth(index int) *Locator

Nth returns a locator that narrows the match to the element at the given index (0-based). Use -1 to select the last element.

func (*Locator) Or

func (l *Locator) Or(other *Locator) *Locator

Or returns a new Locator that matches elements satisfying either this locator or the given locator.

func (*Locator) Press

func (l *Locator) Press(ctx context.Context, key string) error

Press presses a key on the focused element matching the locator.

func (*Locator) PressSequentially

func (l *Locator) PressSequentially(ctx context.Context, text string) error

PressSequentially types text into the element one character at a time, firing keydown/keyup/input events for each character. Uses the "type" IPC (Frame.type) which is the v1.61.1 equivalent.

func (*Locator) Screenshot

func (l *Locator) Screenshot(ctx context.Context, opts ...*ScreenshotOptions) ([]byte, error)

Screenshot captures a screenshot of the element matched by this locator. Returns raw image bytes (PNG by default). Accepts the same ScreenshotOptions as Page.Screenshot.

func (*Locator) ScrollIntoViewIfNeeded

func (l *Locator) ScrollIntoViewIfNeeded(ctx context.Context) error

ScrollIntoViewIfNeeded scrolls the element matched by this locator into the viewport if needed. Uses a two-step querySelector + ElementHandle call because the Playwright v1.61.1 wire protocol does not expose Frame.scrollIntoViewIfNeeded directly.

func (*Locator) SelectOption

func (l *Locator) SelectOption(ctx context.Context, values ...string) ([]string, error)

SelectOption selects one or more options in a <select> element by value. Returns the list of values that were selected.

func (*Locator) Selector

func (l *Locator) Selector() string

Selector returns the CSS/internal selector string used by this locator.

func (*Locator) SetChecked

func (l *Locator) SetChecked(ctx context.Context, checked bool) error

SetChecked sets the checked state of a checkbox or radio element. Uses check/uncheck IPC since Frame.setChecked is not available in Playwright v1.61.1.

func (*Locator) SetInputFiles

func (l *Locator) SetInputFiles(ctx context.Context, paths []string) error

SetInputFiles sets the files on the file input element matched by this locator. paths must be absolute local filesystem paths.

func (*Locator) SetInputFilesPayload

func (l *Locator) SetInputFilesPayload(ctx context.Context, payloads []FilePayload) error

SetInputFilesPayload sets in-memory file payloads on the file input matched by this locator.

func (*Locator) Tap

func (l *Locator) Tap(ctx context.Context) error

Tap performs a tap gesture on the element matched by this locator.

func (*Locator) TextContent

func (l *Locator) TextContent(ctx context.Context) (*string, error)

TextContent returns the text content of the element matched by this locator. Returns nil if the element has no text content (e.g. a void element).

func (*Locator) Uncheck

func (l *Locator) Uncheck(ctx context.Context) error

Uncheck unchecks a checkbox element.

func (*Locator) WaitFor

func (l *Locator) WaitFor(ctx context.Context, state ...string) error

WaitFor waits for the element matched by this locator to satisfy a given state. state can be "attached", "detached", "visible", "hidden". Defaults to "visible".

func (*Locator) WaitForFunction

func (l *Locator) WaitForFunction(ctx context.Context, expression string, arg any, opts ...*LocatorWaitForFunctionOptions) error

WaitForFunction polls the given JavaScript expression until it returns a truthy value, passing the resolved element as the first argument. An optional extra arg is passed as the second. The locator must resolve to exactly one element (strict mode).

type LocatorAriaSnapshotOptions

type LocatorAriaSnapshotOptions struct {
	// Mode controls snapshot generation: "default" (standard ARIA tree) or "ai" (AI-optimized with refs/hints).
	Mode *string
	// Depth limits how many levels deep the snapshot traverses (AI mode only).
	Depth *int
}

LocatorAriaSnapshotOptions configures Locator.AriaSnapshot.

type LocatorAssertions

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

LocatorAssertions provides web-first assertion methods for a Locator. Assertions use the Frame.expect IPC, which retries until the assertion passes or the timeout is exceeded.

func Expect

func Expect(locator *Locator) *LocatorAssertions

Expect creates a new LocatorAssertions for the given Locator.

func (*LocatorAssertions) Not

Not returns a negated version of the assertion.

func (*LocatorAssertions) ToBeAttached

func (a *LocatorAssertions) ToBeAttached(ctx context.Context) error

ToBeAttached asserts that the element is attached to the DOM.

func (*LocatorAssertions) ToBeChecked

func (a *LocatorAssertions) ToBeChecked(ctx context.Context) error

ToBeChecked asserts that the element is checked. The expectedValue must include { checked: true } in serialized form so the Playwright server can extract the boolean via `const { checked } = options.expectedValue`.

func (*LocatorAssertions) ToBeCheckedFalse

func (a *LocatorAssertions) ToBeCheckedFalse(ctx context.Context) error

ToBeCheckedFalse asserts that the element (checkbox/radio) is NOT checked. This is equivalent to expect(locator).not().toBeChecked() but uses the checked:false option. Ref: TestLocatorAssertions.java#isCheckedFalsePass

func (*LocatorAssertions) ToBeCheckedIndeterminate

func (a *LocatorAssertions) ToBeCheckedIndeterminate(ctx context.Context) error

ToBeCheckedIndeterminate asserts that the element (checkbox) is in indeterminate state.

func (*LocatorAssertions) ToBeCheckedWithIndeterminateAndChecked

func (a *LocatorAssertions) ToBeCheckedWithIndeterminateAndChecked(ctx context.Context, checked bool) error

ToBeCheckedWithIndeterminateAndChecked sends both indeterminate=true and checked options together. This combination is invalid per Playwright's protocol; the server returns an error: "Can't assert indeterminate and checked at the same time". Used only in tests that verify proper error handling.

func (*LocatorAssertions) ToBeDetached

func (a *LocatorAssertions) ToBeDetached(ctx context.Context) error

ToBeDetached asserts that the element is NOT attached to the DOM.

func (*LocatorAssertions) ToBeDisabled

func (a *LocatorAssertions) ToBeDisabled(ctx context.Context) error

ToBeDisabled asserts that the element is disabled.

func (*LocatorAssertions) ToBeEditable

func (a *LocatorAssertions) ToBeEditable(ctx context.Context) error

ToBeEditable asserts that the element is editable.

func (*LocatorAssertions) ToBeEmpty

func (a *LocatorAssertions) ToBeEmpty(ctx context.Context) error

ToBeEmpty asserts that the element (input/textarea) is empty or has no child nodes.

func (*LocatorAssertions) ToBeEnabled

func (a *LocatorAssertions) ToBeEnabled(ctx context.Context) error

ToBeEnabled asserts that the element is enabled.

func (*LocatorAssertions) ToBeFocused

func (a *LocatorAssertions) ToBeFocused(ctx context.Context) error

ToBeFocused asserts that the element is focused.

func (*LocatorAssertions) ToBeHidden

func (a *LocatorAssertions) ToBeHidden(ctx context.Context) error

ToBeHidden asserts that the element is not visible.

func (*LocatorAssertions) ToBeInViewport

func (a *LocatorAssertions) ToBeInViewport(ctx context.Context) error

ToBeInViewport asserts that the element intersects the visible viewport.

func (*LocatorAssertions) ToBeReadOnly

func (a *LocatorAssertions) ToBeReadOnly(ctx context.Context) error

ToBeReadOnly asserts that the element is not editable (is readonly or disabled).

func (*LocatorAssertions) ToBeVisible

func (a *LocatorAssertions) ToBeVisible(ctx context.Context) error

ToBeVisible asserts that the element is visible.

func (*LocatorAssertions) ToContainClass

func (a *LocatorAssertions) ToContainClass(ctx context.Context, class string) error

ToContainClass asserts that the element's class list contains the given class name. Unlike ToHaveClass which matches the full class string, ToContainClass checks for inclusion of a specific class within the class attribute. Ref: TestLocatorAssertions.java#containsClassPass

func (*LocatorAssertions) ToContainClassArray

func (a *LocatorAssertions) ToContainClassArray(ctx context.Context, classes []string) error

ToContainClassArray asserts that each element in the matched set contains the corresponding class.

func (*LocatorAssertions) ToContainText

func (a *LocatorAssertions) ToContainText(ctx context.Context, expected string) error

ToContainText asserts that the element contains the expected text (substring match). Uses "to.contain.text.array" which allows the element count to differ from expected count.

func (*LocatorAssertions) ToContainTextArray

func (a *LocatorAssertions) ToContainTextArray(ctx context.Context, expected []string) error

ToContainTextArray asserts that elements contain each expected text (subset, ordered match).

func (*LocatorAssertions) ToContainTextArrayIgnoreCase

func (a *LocatorAssertions) ToContainTextArrayIgnoreCase(ctx context.Context, expected []string) error

ToContainTextArrayIgnoreCase asserts elements contain each expected text, case-insensitively.

func (*LocatorAssertions) ToContainTextIgnoreCase

func (a *LocatorAssertions) ToContainTextIgnoreCase(ctx context.Context, expected string) error

ToContainTextIgnoreCase asserts that the element contains the expected text, ignoring case.

func (*LocatorAssertions) ToContainTextRegex

func (a *LocatorAssertions) ToContainTextRegex(ctx context.Context, re *regexp.Regexp) error

ToContainTextRegex asserts that the element contains text matching the given regular expression. Ref: TestLocatorAssertions.java#containsTextWRegexPass

func (*LocatorAssertions) ToHaveAccessibleDescription

func (a *LocatorAssertions) ToHaveAccessibleDescription(ctx context.Context, expected string) error

ToHaveAccessibleDescription asserts that the element has the given ARIA accessible description.

func (*LocatorAssertions) ToHaveAccessibleDescriptionIgnoreCase

func (a *LocatorAssertions) ToHaveAccessibleDescriptionIgnoreCase(ctx context.Context, text string) error

ToHaveAccessibleDescriptionIgnoreCase asserts the element has the given accessible description, ignoring case.

func (*LocatorAssertions) ToHaveAccessibleDescriptionRegex

func (a *LocatorAssertions) ToHaveAccessibleDescriptionRegex(ctx context.Context, re *regexp.Regexp) error

ToHaveAccessibleDescriptionRegex asserts the element has an accessible description matching the regex.

func (*LocatorAssertions) ToHaveAccessibleErrorMessage

func (a *LocatorAssertions) ToHaveAccessibleErrorMessage(ctx context.Context, text string) error

ToHaveAccessibleErrorMessage asserts the element has the given ARIA error message.

func (*LocatorAssertions) ToHaveAccessibleErrorMessageIgnoreCase

func (a *LocatorAssertions) ToHaveAccessibleErrorMessageIgnoreCase(ctx context.Context, text string) error

ToHaveAccessibleErrorMessageIgnoreCase asserts the element's ARIA error message matches the text, ignoring case.

func (*LocatorAssertions) ToHaveAccessibleErrorMessageRegex

func (a *LocatorAssertions) ToHaveAccessibleErrorMessageRegex(ctx context.Context, re *regexp.Regexp) error

ToHaveAccessibleErrorMessageRegex asserts the element's ARIA error message matches the regex.

func (*LocatorAssertions) ToHaveAccessibleName

func (a *LocatorAssertions) ToHaveAccessibleName(ctx context.Context, expected string) error

ToHaveAccessibleName asserts that the element has the given ARIA accessible name.

func (*LocatorAssertions) ToHaveAccessibleNameIgnoreCase

func (a *LocatorAssertions) ToHaveAccessibleNameIgnoreCase(ctx context.Context, text string) error

ToHaveAccessibleNameIgnoreCase asserts the element has the given accessible name, ignoring case.

func (*LocatorAssertions) ToHaveAccessibleNameRegex

func (a *LocatorAssertions) ToHaveAccessibleNameRegex(ctx context.Context, re *regexp.Regexp) error

ToHaveAccessibleNameRegex asserts the element has an accessible name matching the regex.

func (*LocatorAssertions) ToHaveAttribute

func (a *LocatorAssertions) ToHaveAttribute(ctx context.Context, name, value string) error

ToHaveAttribute asserts that the element has an attribute with the given name and value.

func (*LocatorAssertions) ToHaveAttributeIgnoreCase

func (a *LocatorAssertions) ToHaveAttributeIgnoreCase(ctx context.Context, name, value string) error

ToHaveAttributeIgnoreCase asserts that the element has an attribute with the given value, ignoring case differences. Ref: TestLocatorAssertions.java#hasAttributeTextIgnoreCase

func (*LocatorAssertions) ToHaveAttributeRegex

func (a *LocatorAssertions) ToHaveAttributeRegex(ctx context.Context, name string, re *regexp.Regexp) error

ToHaveAttributeRegex asserts that the element has an attribute whose value matches the regex. Ref: TestLocatorAssertions.java#hasAttributeRegExpPass

func (*LocatorAssertions) ToHaveCSS

func (a *LocatorAssertions) ToHaveCSS(ctx context.Context, name, value string) error

ToHaveCSS asserts that the element has a computed CSS property with the expected value.

func (*LocatorAssertions) ToHaveCSSRegex

func (a *LocatorAssertions) ToHaveCSSRegex(ctx context.Context, name string, re *regexp.Regexp) error

ToHaveCSSRegex asserts that the element's computed CSS property value matches the regex. Ref: TestLocatorAssertions.java#hasCSSRegExPass

func (*LocatorAssertions) ToHaveClass

func (a *LocatorAssertions) ToHaveClass(ctx context.Context, expected string) error

ToHaveClass asserts that the element has the expected CSS class.

func (*LocatorAssertions) ToHaveClassArray

func (a *LocatorAssertions) ToHaveClassArray(ctx context.Context, classes []string) error

ToHaveClassArray asserts that each element has the corresponding class string (full match).

func (*LocatorAssertions) ToHaveClassRegex

func (a *LocatorAssertions) ToHaveClassRegex(ctx context.Context, re *regexp.Regexp) error

ToHaveClassRegex asserts that the element's class attribute matches the given regular expression. Ref: TestLocatorAssertions.java#hasClassRegExpPass

func (*LocatorAssertions) ToHaveClassRegexArray

func (a *LocatorAssertions) ToHaveClassRegexArray(ctx context.Context, res []*regexp.Regexp) error

ToHaveClassRegexArray asserts each element's class attribute matches the corresponding regex.

func (*LocatorAssertions) ToHaveCount

func (a *LocatorAssertions) ToHaveCount(ctx context.Context, count int) error

ToHaveCount asserts that the number of elements matching the locator equals count.

func (*LocatorAssertions) ToHaveID

func (a *LocatorAssertions) ToHaveID(ctx context.Context, expected string) error

ToHaveID asserts that the element has the expected id attribute.

func (*LocatorAssertions) ToHaveJSProperty

func (a *LocatorAssertions) ToHaveJSProperty(ctx context.Context, name string, value any) error

ToHaveJSProperty asserts that the element has a JavaScript property with the expected value. The server expects a SerializedArgument envelope {"value": <SerializedValue>, "handles": []}, then deserializes it and compares with the element property via deepEquals.

func (*LocatorAssertions) ToHaveRole

func (a *LocatorAssertions) ToHaveRole(ctx context.Context, role string) error

ToHaveRole asserts that the element has the given ARIA role.

func (*LocatorAssertions) ToHaveText

func (a *LocatorAssertions) ToHaveText(ctx context.Context, expected string) error

ToHaveText asserts that the element's text matches the expected string. Uses exact matching with whitespace normalization.

func (*LocatorAssertions) ToHaveTextArray

func (a *LocatorAssertions) ToHaveTextArray(ctx context.Context, expected []string) error

ToHaveTextArray asserts that each element in the matched set has a text matching the corresponding entry in the expected slice (ordered, substring match). Ref: TestLocatorAssertions.java#hasTextWTextArrayPass

func (*LocatorAssertions) ToHaveTextArrayIgnoreCase

func (a *LocatorAssertions) ToHaveTextArrayIgnoreCase(ctx context.Context, expected []string) error

ToHaveTextArrayIgnoreCase asserts each element has text matching the array entry, case-insensitively.

func (*LocatorAssertions) ToHaveTextIgnoreCase

func (a *LocatorAssertions) ToHaveTextIgnoreCase(ctx context.Context, expected string) error

ToHaveTextIgnoreCase asserts that the element's text matches the expected string, ignoring case.

func (*LocatorAssertions) ToHaveTextRegex

func (a *LocatorAssertions) ToHaveTextRegex(ctx context.Context, re *regexp.Regexp) error

ToHaveTextRegex asserts that the element's text matches the given regular expression. Ref: TestLocatorAssertions.java#hasTextWRegexPass

func (*LocatorAssertions) ToHaveTextRegexArray

func (a *LocatorAssertions) ToHaveTextRegexArray(ctx context.Context, res []*regexp.Regexp) error

ToHaveTextRegexArray asserts each element's text matches the corresponding regex in the slice.

func (*LocatorAssertions) ToHaveTextRegexIgnoreCase

func (a *LocatorAssertions) ToHaveTextRegexIgnoreCase(ctx context.Context, re *regexp.Regexp, ignoreCase bool) error

ToHaveTextRegexIgnoreCase asserts element text matches the regex source with an explicit ignoreCase override.

func (*LocatorAssertions) ToHaveTextUseInnerText

func (a *LocatorAssertions) ToHaveTextUseInnerText(ctx context.Context, expected string) error

ToHaveTextUseInnerText asserts the element's innerText matches the expected string.

func (*LocatorAssertions) ToHaveValue

func (a *LocatorAssertions) ToHaveValue(ctx context.Context, expected string) error

ToHaveValue asserts that an input element has the expected value.

func (*LocatorAssertions) ToHaveValueRegex

func (a *LocatorAssertions) ToHaveValueRegex(ctx context.Context, re *regexp.Regexp) error

ToHaveValueRegex asserts that an input element's value matches the given regular expression. Ref: TestLocatorAssertions.java#hasValueRegExpPass

func (*LocatorAssertions) ToHaveValues

func (a *LocatorAssertions) ToHaveValues(ctx context.Context, values []string) error

ToHaveValues asserts that a multi-select element has all the specified selected values.

func (*LocatorAssertions) ToHaveValuesRegex

func (a *LocatorAssertions) ToHaveValuesRegex(ctx context.Context, res []*regexp.Regexp) error

ToHaveValuesRegex asserts that a multi-select element's selected values match the given regexes.

func (*LocatorAssertions) ToMatchAriaSnapshot

func (a *LocatorAssertions) ToMatchAriaSnapshot(ctx context.Context, expected string) error

ToMatchAriaSnapshot asserts that the element's ARIA accessibility tree matches the expected YAML snapshot string. Delegates to the Playwright server for structured YAML subset matching (requires Playwright v1.49+).

type LocatorClickOptions

type LocatorClickOptions struct {
	Button      *string  // "left" (default), "right", or "middle"
	ClickCount  *int     // number of clicks (default 1)
	Delay       *float64 // ms between mousedown and mouseup
	Force       *bool    // bypass actionability checks
	Modifiers   []string
	NoWaitAfter *bool
	Position    *struct{ X, Y float64 } // click offset relative to element top-left
	Steps       *int
	Scroll      *string
	Timeout     *float64 // override default timeout in ms
	Trial       *bool    // perform actionability checks without clicking
}

LocatorClickOptions specifies optional parameters for Locator.Click.

type LocatorFilterOptions

type LocatorFilterOptions struct {
	// HasText restricts to elements whose text content includes this string (case-insensitive substring).
	HasText *string
	// HasTextRegex restricts to elements whose text content matches this regular expression.
	HasTextRegex *regexp.Regexp
	// HasNotText restricts to elements whose text content does NOT include this string.
	HasNotText *string
	// HasNotTextRegex restricts to elements whose text content does NOT match this regular expression.
	HasNotTextRegex *regexp.Regexp
	// Has restricts to elements that contain a descendant matching the given Locator.
	Has *Locator
	// HasNot restricts to elements that do NOT contain a descendant matching the given Locator.
	HasNot *Locator
	// Visible, when true, restricts to visible elements; when false, to hidden elements.
	Visible *bool
}

LocatorFilterOptions contains options for narrowing a Locator's match set.

type LocatorWaitForFunctionOptions

type LocatorWaitForFunctionOptions struct {
	// Timeout in milliseconds. 0 uses the server default; negative disables the timeout.
	Timeout float64
}

LocatorWaitForFunctionOptions configures Locator.WaitForFunction behavior.

type Mouse

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

Mouse provides mouse input methods for a page, addressing elements by viewport coordinates. Access via Page.Mouse.

func (*Mouse) Click

func (m *Mouse) Click(ctx context.Context, x, y float64, button ...string) error

Click moves to (x, y) and performs a mouse click. button is optional and defaults to "left".

func (*Mouse) DblClick

func (m *Mouse) DblClick(ctx context.Context, x, y float64, button ...string) error

DblClick moves to (x, y) and performs a double-click. button is optional and defaults to "left".

func (*Mouse) Down

func (m *Mouse) Down(ctx context.Context, button ...string) error

Down presses a mouse button at the current position. button is optional and defaults to "left".

func (*Mouse) Move

func (m *Mouse) Move(ctx context.Context, x, y float64) error

Move moves the mouse to the given (x, y) coordinates.

func (*Mouse) Up

func (m *Mouse) Up(ctx context.Context, button ...string) error

Up releases a mouse button at the current position. button is optional and defaults to "left".

func (*Mouse) Wheel

func (m *Mouse) Wheel(ctx context.Context, deltaX, deltaY float64) error

Wheel dispatches a wheel event at the current mouse position.

type MultipartField

type MultipartField struct {
	Name     string
	Value    string // text value (mutually exclusive with FilePath)
	FilePath string // path to file to upload (mutually exclusive with Value)
}

MultipartField is a field in a multipart/form-data request. Exactly one of Value or FilePath must be set. When FilePath is set the file is read from disk; the MIME type is inferred from the extension.

type NetworkRequest

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

NetworkRequest represents an HTTP request intercepted or observed by the browser.

func (*NetworkRequest) Headers

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

Headers returns request headers as a name→value map.

func (*NetworkRequest) IsNavigationRequest

func (r *NetworkRequest) IsNavigationRequest() bool

IsNavigationRequest reports whether this is a navigation request.

func (*NetworkRequest) Method

func (r *NetworkRequest) Method() string

Method returns the HTTP method (GET, POST, etc.).

func (*NetworkRequest) PostData

func (r *NetworkRequest) PostData() string

PostData returns the request body as a string, or empty string if there is none.

func (*NetworkRequest) PostDataBuffer

func (r *NetworkRequest) PostDataBuffer() []byte

PostDataBuffer returns the request body as raw bytes, or nil if there is none.

func (*NetworkRequest) ResourceType

func (r *NetworkRequest) ResourceType() string

ResourceType returns the resource type (document, stylesheet, image, etc.).

func (*NetworkRequest) Response

func (r *NetworkRequest) Response(ctx context.Context) (*NetworkResponse, error)

Response returns the matching NetworkResponse for this request, or nil if none.

func (*NetworkRequest) Sizes

func (r *NetworkRequest) Sizes(ctx context.Context) (*RequestSizes, error)

Sizes returns byte-level size information for this request and its response.

func (*NetworkRequest) URL

func (r *NetworkRequest) URL() string

URL returns the full request URL.

type NetworkResponse

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

NetworkResponse represents an HTTP response observed by the browser.

func (*NetworkResponse) Body

func (r *NetworkResponse) Body(ctx context.Context) ([]byte, error)

Body returns the response body as raw bytes.

func (*NetworkResponse) Headers

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

Headers returns response headers as a name→value map.

func (*NetworkResponse) OK

func (r *NetworkResponse) OK() bool

OK returns true if the HTTP status code is in the range 200–299.

func (*NetworkResponse) Status

func (r *NetworkResponse) Status() int

Status returns the HTTP status code.

func (*NetworkResponse) StatusText

func (r *NetworkResponse) StatusText() string

StatusText returns the HTTP status text (e.g. "OK", "Not Found").

func (*NetworkResponse) Text

func (r *NetworkResponse) Text(ctx context.Context) (string, error)

Text returns the response body as a UTF-8 string.

func (*NetworkResponse) URL

func (r *NetworkResponse) URL() string

URL returns the response URL (may differ from request URL after redirects).

type OriginStorage

type OriginStorage struct {
	Origin       string              `json:"origin"`
	LocalStorage []LocalStorageEntry `json:"localStorage"`
}

OriginStorage represents localStorage key-values for a given origin.

type Page

type Page struct {
	Keyboard *Keyboard // keyboard input controller for this page
	Mouse    *Mouse    // mouse input controller for this page
	// contains filtered or unexported fields
}

Page provides methods to interact with a single tab in a Browser, or an extension background page in Chromium.

func (*Page) AddInitScript

func (p *Page) AddInitScript(ctx context.Context, script string) error

AddInitScript injects a JavaScript script that runs before any page script on every navigation. Useful for mocking globals, stubbing APIs, or seeding state.

func (*Page) AddLocatorHandler

func (p *Page) AddLocatorHandler(ctx context.Context, locator *Locator, handler func(*Locator), opts ...AddLocatorHandlerOptions) (func(), error)

AddLocatorHandler registers a handler that Playwright calls automatically when the given locator becomes visible during a page interaction (e.g. a cookie banner overlay). The handler must dismiss or hide the element before returning. The returned cancel function unregisters the handler.

func (*Page) BringToFront

func (p *Page) BringToFront(ctx context.Context) error

BringToFront brings the page to the front (activates the tab).

func (*Page) ClearPageErrors

func (p *Page) ClearPageErrors(_ context.Context) error

ClearPageErrors resets the accumulated page error list.

func (*Page) Close

func (p *Page) Close(ctx context.Context) error

Close closes the page and marks its internal state as closed. It is idempotent: later calls perform no action and return nil.

Fail-fast design: local state p.closed is updated to true immediately to prevent redundant concurrent calls. If the underlying IPC call fails due to driver disconnection, the Playwright server automatically reaps remote resources on process exit.

func (*Page) Content

func (p *Page) Content(ctx context.Context) (string, error)

Content returns the full HTML contents of the page.

func (*Page) Context

func (p *Page) Context() *BrowserContext

Context returns the BrowserContext to which this page belongs.

func (*Page) DispatchEvent

func (p *Page) DispatchEvent(ctx context.Context, selector, eventType string, eventInit ...any) error

DispatchEvent dispatches an event of the given type on the first element matching selector. eventInit can optionally provide event initialization data (passed as-is to the event constructor).

func (*Page) DragTo

func (p *Page) DragTo(ctx context.Context, sourceSelector, targetSelector string) error

DragTo performs a drag-and-drop from the element matching sourceSelector to targetSelector.

func (*Page) EmulateMedia

func (p *Page) EmulateMedia(ctx context.Context, opts ...*EmulateMediaOptions) error

EmulateMedia overrides the CSS media type and/or color scheme for the page.

func (*Page) EvalOnSelector

func (p *Page) EvalOnSelector(ctx context.Context, selector, expression string, arg ...any) (any, error)

EvalOnSelector evaluates an expression on the first element matching selector and returns the result. Equivalent to document.querySelector(selector) followed by element.evaluate(expression, arg).

func (*Page) EvalOnSelectorAll

func (p *Page) EvalOnSelectorAll(ctx context.Context, selector, expression string, arg ...any) (any, error)

EvalOnSelectorAll evaluates an expression on all elements matching selector and returns the result. Equivalent to document.querySelectorAll(selector) followed by NodeList.evaluate(expression, arg).

func (*Page) Evaluate

func (p *Page) Evaluate(ctx context.Context, expression string, arg ...any) (any, error)

Evaluate executes a JavaScript expression or function in the context of the main frame and returns the deserialized result.

func (*Page) ExposeBinding added in v1.0.3

func (p *Page) ExposeBinding(ctx context.Context, name string, handler BindingHandler) error

ExposeBinding exposes a Go function as a global JavaScript function on this page only. When JavaScript calls window[name](...args), handler is invoked with the deserialized args. Unlike BrowserContext.ExposeBinding, this is scoped to the single page.

func (*Page) Frame

func (p *Page) Frame(name string) *Frame

Frame returns the first child frame with the given name attribute, or nil if not found.

func (*Page) FrameByURL

func (p *Page) FrameByURL(urlPattern string) *Frame

FrameByURL returns the first child frame whose URL matches the given pattern, or nil if not found. A trailing * means prefix matching; otherwise exact match.

func (*Page) FrameLocator

func (p *Page) FrameLocator(selector string) *FrameLocator

FrameLocator returns a FrameLocator scoped to the first iframe matching selector. All locator operations on the returned FrameLocator target elements inside the iframe.

func (*Page) Frames

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

Frames returns all frames currently attached to the page, including the main frame as the first element.

func (*Page) GetByAltText

func (p *Page) GetByAltText(text string, opts ...*GetByAltTextOptions) *Locator

GetByAltText returns a Locator for elements with the given alt text.

func (*Page) GetByLabel

func (p *Page) GetByLabel(text string, opts ...*GetByLabelOptions) *Locator

GetByLabel returns a Locator for form elements associated with the given label text.

func (*Page) GetByPlaceholder

func (p *Page) GetByPlaceholder(text string, opts ...*GetByPlaceholderOptions) *Locator

GetByPlaceholder returns a Locator for input elements with the given placeholder text.

func (*Page) GetByRole

func (p *Page) GetByRole(role AriaRole, opts ...*GetByRoleOptions) *Locator

GetByRole returns a Locator for elements matching the given ARIA role.

func (*Page) GetByTestId

func (p *Page) GetByTestId(testId string) *Locator

GetByTestId returns a Locator for elements with the configured testid attribute. The attribute name defaults to "data-testid" and can be changed with BrowserContext.SetTestIdAttribute.

func (*Page) GetByText

func (p *Page) GetByText(text string, opts ...*GetByTextOptions) *Locator

GetByText returns a Locator for elements containing the given text.

func (*Page) GetByTitle

func (p *Page) GetByTitle(text string, opts ...*GetByTitleOptions) *Locator

GetByTitle returns a Locator for elements with the given title attribute.

func (*Page) GoBack

func (p *Page) GoBack(ctx context.Context) error

GoBack navigates to the previous page in the session history.

func (*Page) GoForward

func (p *Page) GoForward(ctx context.Context) error

GoForward navigates to the next page in the session history.

func (*Page) Goto

func (p *Page) Goto(ctx context.Context, url string, opts ...*PageGotoOptions) error

Goto navigates the page to the specified URL.

func (*Page) HideHighlight

func (p *Page) HideHighlight(ctx context.Context) error

HideHighlight removes all active element highlights on the page.

func (*Page) IsClosed

func (p *Page) IsClosed() bool

IsClosed returns true if the page has been closed.

func (*Page) Locator

func (p *Page) Locator(selector string) *Locator

Locator returns a new Locator for the given CSS/attribute selector.

func (*Page) MainFrame

func (p *Page) MainFrame() *Frame

MainFrame returns the main (top-level) frame of the page.

func (*Page) OnConsole

func (p *Page) OnConsole(handler func(*ConsoleMessage)) func()

OnConsole registers a handler for console messages emitted by this page. The handler is called from a goroutine for each message. Console events are emitted on the BrowserContext channel; events from other pages in the same context are filtered out. The returned function cancels the listener when called.

func (*Page) OnDOMContentLoaded

func (p *Page) OnDOMContentLoaded(handler func(*Page)) func()

OnDOMContentLoaded registers a handler that fires when the page's "DOMContentLoaded" event fires. The returned function cancels the listener.

func (*Page) OnDialog

func (p *Page) OnDialog(handler func(*Dialog)) func()

OnDialog registers a handler for browser dialogs on this page. The handler is called in a goroutine when the browser emits a "dialog" event. The handler MUST call dialog.Accept or dialog.Dismiss; otherwise the page hangs. Note: the BrowserContext dialog event does not carry a page reference in the wire protocol, so the handler fires for dialogs from ANY page in the same context. The returned function cancels the listener when called.

func (*Page) OnDownload

func (p *Page) OnDownload(handler func(*Download)) func()

OnDownload registers a handler for file downloads initiated by this page. The handler is called in a goroutine for each download. The returned function cancels the listener.

func (*Page) OnFileChooser

func (p *Page) OnFileChooser(handler func(*FileChooser)) func()

OnFileChooser registers a handler that fires when a file chooser dialog is opened on this page. The returned function cancels the listener.

func (*Page) OnLoad

func (p *Page) OnLoad(handler func(*Page)) func()

OnLoad registers a handler that fires when the page's "load" event fires. The returned function cancels the listener.

func (*Page) OnPopup

func (p *Page) OnPopup(fn func(*Page)) func()

OnPopup registers a handler that fires whenever this page opens a popup via window.open() or a link with target="_blank". The returned function cancels the listener.

func (*Page) OnRequest

func (p *Page) OnRequest(handler func(*NetworkRequest)) func()

OnRequest registers a handler that fires for every network request made by this page. The handler receives a NetworkRequest with URL, method, headers, and resource type. The returned function cancels the listener.

func (*Page) OnRequestFailed

func (p *Page) OnRequestFailed(handler func(*NetworkRequest)) func()

OnRequestFailed registers a handler for network requests that have failed. The handler receives a NetworkRequest. The returned function cancels the listener.

func (*Page) OnRequestFinished

func (p *Page) OnRequestFinished(handler func(*NetworkRequest)) func()

OnRequestFinished registers a handler for network requests that have completed successfully. The handler receives a NetworkRequest. The returned function cancels the listener.

func (*Page) OnResponse

func (p *Page) OnResponse(handler func(*NetworkResponse)) func()

OnResponse registers a handler that fires for every HTTP response received by this page. The handler receives a NetworkResponse with URL, status, and headers. The returned function cancels the listener.

func (*Page) OnWebSocket

func (p *Page) OnWebSocket(handler func(*WebSocket)) func()

OnWebSocket registers a handler that fires whenever the page opens a WebSocket connection. The handler receives the new WebSocket and is called in a goroutine. The returned function cancels the listener.

func (*Page) OnWorker

func (p *Page) OnWorker(handler func(*Worker)) func()

OnWorker registers a handler that is called when a new worker is created in this page. The handler receives the new Worker and is called in a goroutine. The returned function cancels the listener.

func (*Page) Opener

func (p *Page) Opener(_ context.Context) (*Page, error)

Opener returns the Page that opened this page via window.open(), or nil if this page was not opened as a popup. Returns (nil, nil) for top-level pages.

func (*Page) PDF

func (p *Page) PDF(ctx context.Context, opts ...*PagePdfOptions) ([]byte, error)

PDF generates a PDF of the page and returns the raw bytes. Only works in headless Chromium.

func (*Page) PageErrors

func (p *Page) PageErrors(_ context.Context) ([]string, error)

PageErrors returns all uncaught exceptions collected since the last ClearPageErrors call. Each entry is formatted as "Name: message" (e.g. "Error: something went wrong"). Errors are tracked via the context-level "pageerror" event started by subscribeToPageErrors.

func (*Page) Pause

func (p *Page) Pause(ctx context.Context) error

Pause pauses script execution. Playwright will stop executing the script and wait for the user to either press 'Resume' button in the page overlay or call playwright.resume().

func (*Page) QuerySelector

func (p *Page) QuerySelector(ctx context.Context, selector string) (*ElementHandle, error)

QuerySelector returns the first element matching the CSS selector, or nil if not found.

func (*Page) QuerySelectorAll

func (p *Page) QuerySelectorAll(ctx context.Context, selector string) ([]*ElementHandle, error)

QuerySelectorAll returns all elements matching the CSS selector.

func (*Page) Reload

func (p *Page) Reload(ctx context.Context) error

Reload reloads the current page and waits for the load event.

func (*Page) RequestGC

func (p *Page) RequestGC(ctx context.Context) error

RequestGC triggers a garbage collection in the page's JavaScript engine. Useful in tests to force GC before checking memory-sensitive behaviour.

func (*Page) Route

func (p *Page) Route(ctx context.Context, pattern string, handler RouteHandler, opts ...*PageRouteOptions) error

Route registers a network interception handler for requests matching the given glob pattern. Multiple calls stack handlers in LIFO order; a handler may call Route.Fallback to defer to the next registered handler.

func (*Page) Screenshot

func (p *Page) Screenshot(ctx context.Context, opts ...*ScreenshotOptions) ([]byte, error)

Screenshot captures a screenshot of the current page viewport. Returns the raw image bytes (PNG by default).

func (*Page) SetContent

func (p *Page) SetContent(ctx context.Context, html string) error

SetContent sets the HTML markup of the page.

func (*Page) SetDefaultNavigationTimeout added in v1.0.3

func (p *Page) SetDefaultNavigationTimeout(ctx context.Context, timeout float64) error

SetDefaultNavigationTimeout sets the default timeout for navigation operations (in milliseconds).

func (*Page) SetDefaultTimeout added in v1.0.3

func (p *Page) SetDefaultTimeout(ctx context.Context, timeout float64) error

SetDefaultTimeout sets the default timeout for all actions on this page (in milliseconds).

func (*Page) SetErrorWriter

func (p *Page) SetErrorWriter(w io.Writer)

SetErrorWriter sets the destination for internal diagnostic messages (e.g., route handler panics). If w is nil, os.Stderr is used. Safe to call concurrently.

func (*Page) SetExtraHTTPHeaders

func (p *Page) SetExtraHTTPHeaders(ctx context.Context, headers map[string]string) error

SetExtraHTTPHeaders sets extra HTTP headers sent on every request from this page. Calling with an empty map clears previously set headers.

func (*Page) SetViewportSize

func (p *Page) SetViewportSize(ctx context.Context, width, height int) error

SetViewportSize changes the page viewport to the given dimensions.

func (*Page) Title

func (p *Page) Title(ctx context.Context) (string, error)

Title returns the document title of the current page.

func (*Page) URL

func (p *Page) URL() string

URL returns the current URL of the main frame. Initialized from the Frame initializer and updated via `navigated` events.

func (*Page) Unroute

func (p *Page) Unroute(ctx context.Context) error

Unroute clears all registered network route handlers on the page.

func (*Page) UnrouteAll

func (p *Page) UnrouteAll(ctx context.Context, behavior ...string) error

UnrouteAll removes all registered route handlers and clears network interception patterns.

func (*Page) Video

func (p *Page) Video() *Video

Video returns the Video associated with this page, or nil if recording is not enabled. The video file is only accessible after the page is closed.

func (*Page) ViewportSize

func (p *Page) ViewportSize(_ context.Context) (*ViewportSize, error)

ViewportSize returns the current viewport dimensions.

func (*Page) WaitForClose

func (p *Page) WaitForClose(ctx context.Context, trigger func() error) error

WaitForClose waits for this page to be closed. trigger is called after the listener is registered. Returns when the page fires its "close" event.

func (*Page) WaitForEvent

func (p *Page) WaitForEvent(ctx context.Context, event string) (any, error)

WaitForEvent waits for a page-level event to fire and returns its payload. Supported events: "popup" (*Page), "request" (*NetworkRequest), "response" (*NetworkResponse), "download" (*Download), "websocket" (*WebSocket).

func (*Page) WaitForFileChooser

func (p *Page) WaitForFileChooser(ctx context.Context, trigger func()) (*FileChooser, error)

WaitForFileChooser waits for a file chooser to be opened, executes the trigger function, and returns the resulting FileChooser. It times out after the given deadline from ctx.

func (*Page) WaitForFunction

func (p *Page) WaitForFunction(ctx context.Context, expression string, arg any, opts ...*WaitForFunctionOptions) (*JSHandle, error)

WaitForFunction polls the given JavaScript expression or function until it returns a truthy value, then returns the result wrapped in a JSHandle. If the expression throws, the error propagates.

func (*Page) WaitForLoadState

func (p *Page) WaitForLoadState(ctx context.Context, state ...string) error

WaitForLoadState waits until the page reaches the given load state. Valid states: "load" (default), "domcontentloaded", "networkidle". Delegates to the server-side Frame.waitForLoadState which handles already-reached states correctly, including "networkidle" which has no equivalent DOM readyState to check client-side.

func (*Page) WaitForPopup

func (p *Page) WaitForPopup(ctx context.Context, trigger func() error) (*Page, error)

WaitForPopup registers a popup listener, calls trigger, then waits for a popup to open. trigger is called after the listener is registered to avoid race conditions.

func (*Page) WaitForTimeout

func (p *Page) WaitForTimeout(ctx context.Context, ms float64) error

WaitForTimeout pauses execution for the specified number of milliseconds.

func (*Page) WaitForURL

func (p *Page) WaitForURL(ctx context.Context, pattern string, timeout ...time.Duration) error

WaitForURL waits until the page URL matches the given pattern. The pattern can be an exact URL or end with * for prefix matching. Uses the provided context for cancellation; default timeout is 30s.

func (*Page) WaitForWebSocket

func (p *Page) WaitForWebSocket(ctx context.Context, trigger func() error) (*WebSocket, error)

WaitForWebSocket waits for a WebSocket connection to be created during the execution of the trigger function. trigger is called after the listener is registered to avoid race conditions. Returns the first WebSocket created, or an error if ctx is canceled.

func (*Page) Workers

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

Workers returns the currently active web workers associated with this page.

type PageAssertions

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

PageAssertions provides web-first assertion methods for a Page. All assertions retry automatically until the condition is met or the context deadline is reached.

func ExpectPage

func ExpectPage(page *Page) *PageAssertions

ExpectPage creates a new PageAssertions for the given Page.

func (*PageAssertions) HasTitle

func (a *PageAssertions) HasTitle(ctx context.Context, expected string) error

HasTitle asserts that the page title matches the given string (exact match).

func (*PageAssertions) HasTitleContains

func (a *PageAssertions) HasTitleContains(ctx context.Context, expected string) error

HasTitleContains asserts that the page title contains the expected substring.

func (*PageAssertions) HasTitleRegex

func (a *PageAssertions) HasTitleRegex(ctx context.Context, pattern string) error

HasTitleRegex asserts that the page title matches the given regular expression.

func (*PageAssertions) HasURL

func (a *PageAssertions) HasURL(ctx context.Context, expected string) error

HasURL asserts that the page URL matches the given string (exact match).

func (*PageAssertions) HasURLContains

func (a *PageAssertions) HasURLContains(ctx context.Context, expected string) error

HasURLContains asserts that the page URL contains the expected substring.

func (*PageAssertions) HasURLRegex

func (a *PageAssertions) HasURLRegex(ctx context.Context, pattern string) error

HasURLRegex asserts that the page URL matches the given regular expression.

func (*PageAssertions) Not

func (a *PageAssertions) Not() *PageAssertions

Not returns a negated version of the assertion.

type PageGotoOptions

type PageGotoOptions struct {
	// WaitUntil is the load state to wait for: "load", "domcontentloaded", "networkidle", or "commit".
	WaitUntil *string
	// Referer overrides the HTTP Referer header.
	Referer *string
	// Timeout overrides the default navigation timeout (milliseconds).
	Timeout *float64
}

PageGotoOptions configures the behaviour of Page.Goto.

type PagePdfOptions

type PagePdfOptions struct {
	// DisplayHeaderFooter displays header and footer. Defaults to false.
	DisplayHeaderFooter *bool
	// FooterTemplate is the HTML template for the print footer.
	FooterTemplate *string
	// Format specifies the paper format (e.g. "A4", "Letter"). Takes priority over Width/Height.
	Format *string
	// HeaderTemplate is the HTML template for the print header.
	HeaderTemplate *string
	// Height specifies the paper height, accepts values labeled with units.
	Height *string
	// Landscape renders the page in landscape orientation. Defaults to false.
	Landscape *bool
	// Outline embeds the document outline into the PDF. Defaults to false.
	Outline *bool
	// PageRanges is the paper ranges to print, e.g., "1-5, 8, 11-13". Defaults to all pages.
	PageRanges *string
	// PreferCSSPageSize gives priority to CSS page size declared in the page. Defaults to false.
	PreferCSSPageSize *bool
	// PrintBackground prints background graphics. Defaults to false.
	PrintBackground *bool
	// Scale scales the rendering of the web page. Amount must be between 0.1 and 2. Defaults to 1.
	Scale *float64
	// Tagged generates tagged (accessible) PDF. Defaults to false.
	Tagged *bool
	// Width specifies the paper width, accepts values labeled with units.
	Width *string
}

PagePdfOptions specifies optional parameters for Page.Pdf.

type PageRouteOptions

type PageRouteOptions struct {
	// Times limits how many times the handler is invoked. Zero (default) means unlimited.
	Times *int
}

PageRouteOptions configures optional parameters for Page.Route.

type Playwright

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

Playwright represents the main entry point to the Playwright automation library.

func Run

func Run(ctx context.Context, cliPath string) (*Playwright, error)

Run initializes the Node.js driver, performs the "initialize" handshake with Root, and sets up IPC. The caller's context controls the timeout for the initial handshake. The operational lifecycle of the driver is independent and controlled via Playwright.Stop().

func (*Playwright) Chromium

func (p *Playwright) Chromium() (*BrowserType, error)

Chromium returns the Chromium BrowserType instance.

func (*Playwright) Firefox

func (p *Playwright) Firefox() (*BrowserType, error)

Firefox returns the Firefox BrowserType instance.

func (*Playwright) NewAPIRequestContext

func (p *Playwright) NewAPIRequestContext(ctx context.Context, opts ...*APIRequestContextOptions) (*APIRequestContext, error)

NewAPIRequestContext creates a standalone HTTP request context.

func (*Playwright) Stop

func (p *Playwright) Stop() error

Stop safely terminates the driver process.

func (*Playwright) WebKit

func (p *Playwright) WebKit() (*BrowserType, error)

WebKit returns the WebKit BrowserType instance.

type ProxyOptions

type ProxyOptions struct {
	Server   string  `json:"server"`
	Bypass   *string `json:"bypass,omitempty"`
	Username *string `json:"username,omitempty"`
	Password *string `json:"password,omitempty"`
}

ProxyOptions defines proxy configuration for a BrowserContext.

type RecordVideoOptions

type RecordVideoOptions struct {
	// Dir is the directory in which to store recorded videos.
	Dir string `json:"dir"`
	// Size is the video frame size; defaults to the viewport size.
	Size *ViewportSize `json:"size,omitempty"`
}

RecordVideoOptions configures video recording for a BrowserContext.

type Rect

type Rect struct {
	X      float64
	Y      float64
	Width  float64
	Height float64
}

Rect represents a rectangle for clipping or bounding-box operations.

type RegisterSelectorEngineOptions

type RegisterSelectorEngineOptions struct {
	// ContentScript controls whether the selector engine runs in the page's content script context.
	// When true, the engine runs in an isolated world; when false (the default), it runs in the main world.
	ContentScript *bool
}

RegisterSelectorEngineOptions specifies options for BrowserContext.RegisterSelectorEngine.

type RequestSizes

type RequestSizes struct {
	RequestBodySize     int `json:"requestBodySize"`
	RequestHeadersSize  int `json:"requestHeadersSize"`
	ResponseBodySize    int `json:"responseBodySize"`
	ResponseHeadersSize int `json:"responseHeadersSize"`
}

RequestSizes holds byte-level size information for a request and its response.

type Route

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

Route represents an intercepted network request that can be fulfilled, continued, or aborted.

func (*Route) Abort

func (r *Route) Abort(ctx context.Context, errorCode ...string) error

Abort cancels the intercepted request. An optional errorCode can be provided (defaults to "failed").

func (*Route) Continue

func (r *Route) Continue(ctx context.Context, opts *RouteContinueOptions) error

Continue passes the request to the network with optional modifications.

func (*Route) Fallback

func (r *Route) Fallback(ctx context.Context, opts ...*RouteFallbackOptions) error

Fallback defers handling of this route to the next registered handler. When managed by a routeRouter, it signals the router to proceed to the next entry. When called outside a router context, it sends "continue" with isFallback=true directly to the server.

func (*Route) Fulfill

func (r *Route) Fulfill(ctx context.Context, opts *RouteFulfillOptions) error

Fulfill completes the route with a custom HTTP response.

func (*Route) Request

func (r *Route) Request() *NetworkRequest

Request returns the NetworkRequest associated with this route. The result is cached after the first call.

type RouteContinueOptions

type RouteContinueOptions struct {
	Headers  map[string]string
	Method   *string
	PostData []byte
	URL      *string
}

RouteContinueOptions specifies modifications for Route.Continue.

type RouteFallbackOptions

type RouteFallbackOptions struct {
	// URL overrides the request URL when falling back to the next handler or the network.
	URL *string
}

RouteFallbackOptions configures optional overrides when falling back a route.

type RouteFromHAROptions

type RouteFromHAROptions struct {
	URL *string // glob pattern to restrict which URLs are served from HAR (default: all)
}

RouteFromHAROptions configures BrowserContext.RouteFromHAR.

type RouteFulfillOptions

type RouteFulfillOptions struct {
	Status      *int
	Headers     map[string]string
	Body        *string
	BodyBytes   []byte
	ContentType *string
}

RouteFulfillOptions specifies the response for Route.Fulfill.

type RouteHandler

type RouteHandler func(route *Route)

RouteHandler is the function called when a request matches a route pattern.

type SameSiteAttribute

type SameSiteAttribute string

SameSiteAttribute represents the SameSite policy for cookies.

const (
	SameSiteStrict SameSiteAttribute = "Strict"
	SameSiteLax    SameSiteAttribute = "Lax"
	SameSiteNone   SameSiteAttribute = "None"
)

type ScreenSize

type ScreenSize struct {
	Width  int `json:"width"`
	Height int `json:"height"`
}

ScreenSize defines emulated screen dimensions.

type ScreenshotOptions

type ScreenshotOptions struct {
	// Path is the file path to save the screenshot to. If empty, the screenshot is only returned as bytes.
	Path string
	// Type is "png" (default) or "jpeg".
	Type string
	// Quality is JPEG quality 0–100. Only applies when Type is "jpeg".
	Quality *int
	// FullPage captures the full scrollable page.
	FullPage *bool
	// Clip restricts the screenshot to a sub-rectangle of the viewport.
	Clip *Rect
	// OmitBackground hides the default white background and allows capturing screenshots with transparency.
	OmitBackground *bool
	// Scale is "css" (default) or "device". Use "device" to capture at device pixel ratio.
	Scale string
	// Mask is a list of locators that should be masked (blacked out) in the screenshot.
	Mask []*Locator
}

ScreenshotOptions controls the output format of Page.Screenshot.

type StorageState

type StorageState struct {
	Cookies []Cookie        `json:"cookies,omitempty"`
	Origins []OriginStorage `json:"origins,omitempty"`
}

StorageState contains serialized cookies and localStorage entries to populate a BrowserContext.

type Tracing

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

Tracing provides methods to start and stop Playwright traces. Traces capture browser interactions as a zip archive for later analysis.

func (*Tracing) Start

func (t *Tracing) Start(ctx context.Context, opts ...*TracingStartOptions) error

Start begins a trace recording.

func (*Tracing) StartChunk

func (t *Tracing) StartChunk(ctx context.Context, name ...string) (string, error)

StartChunk begins a new chunk of an ongoing trace recording. Returns the generated trace name.

func (*Tracing) Stop

func (t *Tracing) Stop(ctx context.Context) error

Stop ends the trace recording without saving.

func (*Tracing) StopChunk

func (t *Tracing) StopChunk(ctx context.Context, path string) error

StopChunk ends the current trace chunk. If path is non-empty the trace is saved to that path; otherwise it is discarded.

type TracingStartOptions

type TracingStartOptions struct {
	Name        *string
	Screenshots *bool
	Snapshots   *bool
	Sources     *bool
}

TracingStartOptions configures Tracing.Start.

type Video

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

Video represents a recorded video for a page. The video file is only available after the page (and its recording) is closed.

func (*Video) Delete

func (v *Video) Delete(ctx context.Context) error

Delete removes the recorded video file.

func (*Video) Path

func (v *Video) Path(ctx context.Context) (string, error)

Path waits for the video recording to finish and returns the path to the video file.

func (*Video) SaveAs

func (v *Video) SaveAs(ctx context.Context, path string) error

SaveAs copies the recorded video to the destination path.

type ViewportSize

type ViewportSize struct {
	Width  int `json:"width"`
	Height int `json:"height"`
}

ViewportSize defines the browser window viewport dimensions.

type VirtualCredential

type VirtualCredential struct {
	ID         string `json:"id"`
	RpID       string `json:"rpId"`
	UserHandle string `json:"userHandle"`
	PrivateKey string `json:"privateKey"`
	PublicKey  string `json:"publicKey"`
}

VirtualCredential represents a virtual WebAuthn credential.

type WaitForFunctionOptions

type WaitForFunctionOptions struct {
	PollingInterval float64 // polling interval in ms (0 = requestAnimationFrame)
	Timeout         float64 // timeout in ms (0 = server default ~30s; negative = disable)
}

WaitForFunctionOptions configures WaitForFunction behavior.

type WebSocket

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

WebSocket represents an active WebSocket connection opened from a page. Event handlers are goroutine-safe; all On* calls may be called from any goroutine.

func (*WebSocket) IsClosed

func (ws *WebSocket) IsClosed() bool

IsClosed reports whether the WebSocket connection has been closed.

func (*WebSocket) OnClose

func (ws *WebSocket) OnClose(handler func()) func()

OnClose registers a handler called when the WebSocket connection closes. The returned function cancels the listener.

func (*WebSocket) OnError

func (ws *WebSocket) OnError(handler func(string)) func()

OnError registers a handler called when the WebSocket encounters a socket error. The error string is passed to the handler. The returned function cancels the listener.

func (*WebSocket) OnFrameReceived

func (ws *WebSocket) OnFrameReceived(handler func(WebSocketFrame)) func()

OnFrameReceived registers a handler called for every frame received from the server. The returned function cancels the listener.

func (*WebSocket) OnFrameSent

func (ws *WebSocket) OnFrameSent(handler func(WebSocketFrame)) func()

OnFrameSent registers a handler called for every frame sent to the server. The returned function cancels the listener.

func (*WebSocket) URL

func (ws *WebSocket) URL() string

URL returns the WebSocket endpoint URL (e.g. "ws://localhost:1234/ws").

type WebSocketFrame

type WebSocketFrame struct {
	Data   string
	Opcode int
}

WebSocketFrame represents a single frame transmitted over a WebSocket connection. Opcode 1 = text frame, 2 = binary frame.

func (WebSocketFrame) Text

func (f WebSocketFrame) Text() string

Text returns the frame payload as a UTF-8 string. For binary frames this is still the raw string representation of the data.

type Worker

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

Worker represents a Web Worker associated with a page.

func (*Worker) Evaluate

func (w *Worker) Evaluate(ctx context.Context, expression string, arg ...any) (any, error)

Evaluate executes a JavaScript expression in the worker's context.

func (*Worker) EvaluateHandle

func (w *Worker) EvaluateHandle(ctx context.Context, expression string, arg ...any) (*JSHandle, error)

EvaluateHandle executes a JavaScript expression in the worker and returns the result as a JSHandle.

func (*Worker) URL

func (w *Worker) URL() string

URL returns the URL of the worker script.

Directories

Path Synopsis
cmd
gen command
examples
api-automation
Package apiautomation demonstrates API test automation for the Petstore public API (https://petstore.swagger.io/v2) using the goaneco-playwright Go client with Playwright's APIRequestContext for HTTP requests.
Package apiautomation demonstrates API test automation for the Petstore public API (https://petstore.swagger.io/v2) using the goaneco-playwright Go client with Playwright's APIRequestContext for HTTP requests.
api-automation/models
Package models contains the data transfer objects for the Petstore API.
Package models contains the data transfer objects for the Petstore API.
ui-automation
Package uiautomation demonstrates UI test automation for SauceDemo (https://www.saucedemo.com) using the goaneco-playwright Go client with the Page Object Model (POM) pattern.
Package uiautomation demonstrates UI test automation for SauceDemo (https://www.saucedemo.com) using the goaneco-playwright Go client with the Page Object Model (POM) pattern.
ui-automation/pom
Package pom provides Page Object Model (POM) structs for the SauceDemo website (https://www.saucedemo.com), used by the ui-automation example suite.
Package pom provides Page Object Model (POM) structs for the SauceDemo website (https://www.saucedemo.com), used by the ui-automation example suite.
internal
Code generated by cmd/gen/main.go.
Code generated by cmd/gen/main.go.

Jump to

Keyboard shortcuts

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