Help us shape the future of Go! Take the 2026 Go Developer Survey

rod

package module
v0.120.0 Latest Latest
Warning

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

Go to latest
Published: Sep 6, 2026 License: MIT Imports: 39 Imported by: 0

README

rod

Credits

Rod was created by Yad Smood and developed with the go-rod contributors. This repository is a maintained fork of go-rod/rod. The original and fork copyright notices are preserved in the MIT license.

Overview

A high-level Go driver for the Chrome DevTools Protocol, built for browser automation and scraping.

  • Chainable, context-aware API with automatic waiting
  • Support for nested frames and shadow DOMs
  • Page interaction, request interception, screenshots, PDFs, and downloads
  • Concurrent-safe browser operations
  • Dependency-free core module
  • Direct local browser execution without downloaded binaries

Requirements

  • Go 1.27.1 or later
  • Chrome, Chromium, or Edge installed locally

See the platform support matrix for exact tested OS, CPU, browser, and Go versions, plus known cleanup limitations on other systems.

Rod never downloads a browser or helper executable. Use launcher.Launcher.Bin when an explicit browser path is required. Local launches use a fresh temporary automation profile by default; using an installed browser does not require using its personal profile. Set Launcher.UserDataDir explicitly when session state should persist.

Installation

go get github.com/rah-0/rod

See the API reference. For versioned migration notes, see Breaking changes.

Events

Subscribe before triggering an action, then call the returned wait function:

wait := page.EachEvent(rod.On(func(event *proto.PageLoadEventFired, _ proto.TargetSessionID) bool {
    fmt.Println("page loaded at", event.Timestamp)
    return true
}))
page.MustNavigate("https://example.com")
if err := wait(); err != nil {
    panic(err)
}

Return false to keep receiving events. Pass multiple rod.On handlers to observe different event types in message order. Browser handlers receive events across sessions; page handlers only receive their page's events. For one event, use var event proto.PageLoadEventFired and wait := page.WaitEvent(&event). Cancel the page or browser context to end a continuing subscription.

Runnable examples

The examples start their own browsers and local services. Run a command from the repository root, for example:

go run ./examples/forms
go run ./examples/capture
bash scripts/check.sh examples
Example Demonstrates
Page diagnostics Initial console messages, exceptions, and HTTP failures.
Owned launch Configured process ownership and cleanup after a deadline.
JSON evaluation Typed DOM projection, discarded results, and serialization errors.
Typing Validated keys, Enter actions, and Unicode insertion.
HTTP fixture Relative scripts and API responses with configuration before navigation.
Forms Visibility waits, file uploads, and form submission.
Capture Page and element screenshots, device emulation, and PDF output.
Network Request headers and cookies configured before navigation.
Download Download completion and verification of the saved bytes.
Proxy authentication An authenticated local proxy and verified forwarding.
Connect to a browser Attach to a browser whose process belongs to its caller.
Managed launch An authenticated manager and remotely requested browser lifecycle.
Custom WebSocket A third-party transport adapter with cancellation and cleanup.
E2E test project Native Go tests with a shared process and isolated browser contexts.

Every command has a test that runs its example code and checks browser results. The E2E project runs with go test, and scripts/check.sh examples includes it and the separate custom-WebSocket module. The browser suite includes all examples.

Project backlog

Upstream Rod issues and pull requests have been reviewed and triaged. The retained tasks are documented in the issue backlog and pull-request assessments, with priorities and acceptance criteria.

Development

The core module has no third-party Go dependencies. Protocol serialization uses standard encoding/json; direct encoding/json/v2 imports are prohibited. Regeneration uses checked-in protocol and device snapshots and a local Node.js executable. It runs offline and reproduces the pinned protocol schema:

go generate ./...

See protocol generation and device generation for snapshot provenance and update procedures. Generators validate their output before replacing owned files.

Check formatting, vet, compilation of all four modules with and without the workspace, and race tests that need no browser or container:

bash scripts/check.sh pure
bash scripts/check.sh fix

The second command prints advisory go fix -diff suggestions for review; it does not apply them. Review protocol encoding before applying suggestions, and keep explicit WaitGroup.Add/Done calls around callbacks that may panic or call runtime.Goexit.

Run the root suite and all example modules with an installed browser:

bash scripts/check.sh browser

The test runner runs packages and test cases sequentially (-p=1 -parallel=1). The root suite reuses one browser, retires it after a failed test, and bounds graceful shutdown before killing owned processes and removing profiles. Root and e2e browser cases stay sequential even with a higher -parallel setting. The cleanup benchmark also runs one browser lifecycle at a time.

Executable documentation examples run separately with bash scripts/check.sh live. Tests store screenshots, PDFs, and failed-test CDP logs in t.ArtifactDir(). To retain these files from root tests:

mkdir -p /tmp/rod-artifacts
GODEBUG=tracebackancestors=100 go test -count=1 -race -cover -covermode=atomic \
  -run '^Test' -artifacts -outputdir /tmp/rod-artifacts .

Successful-test CDP logs are removed. Without -artifacts, Go removes artifact directories after the test.

The separate Testcontainers compatibility test uses WithAlwaysPull() to test docker.io/chromedp/headless-shell:latest on every run. The floating tag is intentional so newly published browser versions are checked for compatibility:

go test -count=1 -race -cover -covermode=atomic ./lib/docker

Nested modules retain their local replace directives.

License

Rod is available under the MIT License.

☕ Support

If this saved you time or brought value to your project, feel free to show some support. Every bit is appreciated 🙂

Buy Me A Coffee

Documentation

Overview

Package rod is a high-level driver directly based on DevTools Protocol.

Example (Basic)

This example opens a local page, searches for "git", and then gets the result element which gives the description for Git.

package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/input"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_, _ = fmt.Fprint(w, `<!doctype html>
<html>
<head><title>Repository search</title></head>
<body>
<input id="query-builder-test" name="query">
<span id="result"></span>
<script>
const query = document.querySelector("#query-builder-test")
document.addEventListener("keydown", event => {
	if (event.key === "/") {
		event.preventDefault()
		query.focus()
	}
})
query.addEventListener("keydown", event => {
	if (event.key === "Enter" && query.value.toLowerCase() === "git") {
		document.querySelector("#result").textContent = "Git is the most widely used version control system."
		document.title = "Repository search results"
	}
})
</script>
</body>
</html>`)
	}))
	defer server.Close()

	// Launch a new browser with default options, and connect to it.
	browser := rod.New().MustConnect()

	// Close the implicitly launched browser when this function returns.
	defer browser.MustClose()

	// Create a new page
	page := browser.MustPage(server.URL).MustWaitStable()

	// Trigger the search input with hotkey "/"
	page.Keyboard.MustType(input.Slash)

	// We use css selector to get the search input element and input "git"
	page.MustElement("#query-builder-test").MustInput("git").MustType(input.Enter)

	// Wait until css selector get the element then get the text content of it.
	text := page.MustElementR("span", "most widely used").MustText()

	fmt.Println(text)

	// Get all input elements. Rod supports query elements by css selector, xpath, and regex.
	// For more detailed usage, check the query_test.go file.
	fmt.Println("Found", len(page.MustElements("input")), "input elements")

	// Eval js on the page
	page.MustEval(`() => console.log("hello world")`)

	// Pass parameters as json objects to the js function. This MustEval will result 3
	fmt.Println("1 + 2 =", page.MustEval(`(a, b) => a + b`, 1, 2).Int())

	// When eval on an element, "this" in the js is the current DOM element.
	fmt.Println(page.MustElement("title").MustEval(`() => this.innerText`).String())

}
Output:
Git is the most widely used version control system.
Found 1 input elements
1 + 2 = 3
Repository search results
Example (Context_and_EachEvent)
package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://github.com").MustWaitLoad()

	page, cancel := page.WithCancel()

	go func() {
		time.Sleep(time.Second)
		cancel()
	}()

	// It's a blocking method, it will wait until the context is cancelled
	err := page.EachEvent(rod.On(func(_ *proto.PageLifecycleEvent, _ proto.TargetSessionID) bool { return false }))()

	if errors.Is(err, context.Canceled) {
		fmt.Println("cancelled")
	} else {
		utils.E(err)
	}
}
Example (Context_and_timeout)

Rod use https://golang.org/pkg/context to handle cancellations for IO blocking operations, most times it's timeout. Context will be recursively passed to all sub-methods. For example, methods like Page.Context(ctx) will return a clone of the page with the ctx, all the methods of the returned page will use the ctx if they have IO blocking operations. Page.Timeout or Page.WithCancel is just a shortcut for Page.Context. Of course, Browser or Element works the same way.

package main

import (
	"math/rand/v2"
	"time"

	"github.com/rah-0/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://github.com")

	page.
		// Set a 5-second timeout for all chained methods
		Timeout(5 * time.Second).

		// The total time for MustWaitLoad and MustElement must be less than 5 seconds
		MustWaitLoad().
		MustElement("title").

		// Methods after CancelTimeout won't be affected by the 5-second timeout
		CancelTimeout().

		// Set a 10-second timeout for all chained methods
		Timeout(10 * time.Second).

		// Panics if it takes more than 10 seconds
		MustText()

	// The two code blocks below are basically the same:
	{
		page.Timeout(5 * time.Second).MustElement("a").CancelTimeout()
	}
	{
		// Use this way you can customize your own way to cancel long-running task
		page, cancel := page.WithCancel()
		go func() {
			time.Sleep(time.Duration(rand.Int())) // cancel after randomly time
			cancel()
		}()
		page.MustElement("a")
	}
}
Example (Customize_browser_launch)

Shows how we can further customize the browser with the launcher library. Usually you use launcher lib to set the browser's command line flags (switches). Doc for flags: https://peter.sh/experiments/chromium-command-line-switches

package main

import (
	"fmt"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/launcher"
)

func main() {
	l := launcher.New().
		Proxy("127.0.0.1:8080").    // set flag "--proxy-server=127.0.0.1:8080"
		Delete("use-mock-keychain") // delete flag "--use-mock-keychain"
	defer func() {
		l.Kill()
		l.Cleanup()
	}()
	url := l.MustLaunch()

	browser := rod.New().ControlURL(url).MustConnect()
	defer browser.MustClose()

	// So that we don't have to self issue certs for MITM
	browser.MustIgnoreCertErrors(true)

	// Adding authentication to the proxy, for the next auth request.
	// We use CLI tool "mitmproxy --proxyauth user:pass" as an example.
	go browser.MustHandleAuth("user", "pass")()

	// mitmproxy needs a cert config to support https. We use http here instead,
	// for example
	fmt.Println(browser.MustPage("https://mdn.dev/").MustElement("title").MustText())
}
Example (Customize_retry_strategy)

Shows how to change the retry/polling options that is used to query elements. This is useful when you want to customize the element query retry logic.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	browser := rod.New().Context(ctx).NoDefaultDevice().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage().MustSetDocumentContent(`<input name="query">`)

	// Each query gets its own retry count and a delay that respects cancellation.
	sleeper := func() utils.Sleeper {
		return utils.EachSleepers(
			utils.CountSleeper(3),
			utils.BackoffSleeper(10*time.Millisecond, 100*time.Millisecond, nil),
		)
	}
	el, err := page.Sleeper(sleeper).Element("input")
	utils.E(err)
	fmt.Println(el.MustProperty("name"))

	_, err = page.Sleeper(sleeper).Element("#missing")
	if limit, ok := errors.AsType[*utils.MaxSleepCountError](err); ok {
		fmt.Println("retry limit:", limit.Max)
	} else {
		utils.E(err)
	}

	// NotFoundSleeper returns an ElementNotFoundError without retrying.
	_, err = page.Sleeper(rod.NotFoundSleeper).Element("#missing")
	if errors.Is(err, &rod.ElementNotFoundError{}) {
		fmt.Println("element not found")
	} else if err != nil {
		panic(err)
	}

}
Output:
query
retry limit: 3
element not found
Example (Direct_cdp)

When rod doesn't have a feature that you need. You can easily call the cdp to achieve it. List of cdp API: https://github.com/rah-0/rod/tree/main/lib/proto

package main

import (
	"context"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage()

	// Rod doesn't have a method to enable AD blocking,
	// but you can call cdp interface directly to achieve it.

	// The two code blocks below are equal to enable AD blocking

	{
		_ = proto.PageSetAdBlockingEnabled{
			Enabled: true,
		}.Call(page)
	}

	{
		// Interact with the cdp JSON API directly
		_, _ = page.Call(context.TODO(), "", "Page.setAdBlockingEnabled", map[string]bool{
			"enabled": true,
		})
	}
}
Example (Disable_headless_to_debug)

Shows how to disable headless mode and debug. Rod provides a lot of debug options, you can set them with setter methods or command-line defaults. Doc for command-line defaults: https://pkg.go.dev/github.com/rah-0/rod/lib/defaults

package main

import (
	"fmt"
	"time"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/input"
	"github.com/rah-0/rod/lib/launcher"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	// Headless runs the browser on foreground, you can also use flag "-rod=show"
	// Devtools opens the tab in each new tab opened automatically
	l := launcher.New().
		Headless(false).
		Devtools(true)

	defer func() {
		l.Kill()
		l.Cleanup()
	}()
	url := l.MustLaunch()

	// Trace shows verbose debug information for each action executed
	// SlowMotion is a debug related function that waits 2 seconds between
	// each action, making it easier to inspect what your code is doing.
	browser := rod.New().
		ControlURL(url).
		Trace(true).
		SlowMotion(2 * time.Second).
		MustConnect()

	// ServeMonitor plays screenshots of each tab. This feature is extremely
	// useful when debugging with headless mode.
	// You can also enable it with flag "-rod=monitor"
	launcher.Open(browser.ServeMonitor(""))

	defer browser.MustClose()

	page := browser.MustPage("https://github.com/")

	page.MustElement("input").MustInput("git").MustType(input.Enter)

	text := page.MustElement(".codesearch-results p").MustText()

	fmt.Println(text)

	utils.Pause() // pause goroutine
}
Example (Download_file)
package main

import (
	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://file-examples.com/index.php/sample-documents-download/sample-pdf-download/")

	wait := browser.MustWaitDownload()

	page.MustElementR("a", "DOWNLOAD SAMPLE PDF FILE").MustClick()

	_ = utils.OutputFile("t.pdf", wait())
}
Example (Error_handling)

We use "Must" prefixed functions to write example code. But in production you may want to use the no-prefix version of them. About why we use "Must" as the prefix, it's similar to https://golang.org/pkg/regexp/#MustCompile

package main

import (
	"context"
	"errors"
	"fmt"

	"github.com/rah-0/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://mdn.dev")

	// We use Go's standard way to check error types, no magic.
	check := func(err error) {
		if errors.Is(err, context.DeadlineExceeded) { // timeout error
			fmt.Println("timeout err")
		} else if evalErr, ok := errors.AsType[*rod.EvalError](err); ok { // eval error
			fmt.Println(evalErr.LineNumber)
		} else if err != nil {
			fmt.Println("can't handle", err)
		}
	}

	// The two code blocks below are doing the same thing in two styles:

	// The block below is better for debugging or quick scripting. We use panic to short-circuit logics.
	// So that we can take advantage of fluent interface (https://en.wikipedia.org/wiki/Fluent_interface)
	// and fail-fast (https://en.wikipedia.org/wiki/Fail-fast).
	// This style will reduce code, but it may also catch extra errors (less consistent and precise).
	{
		err := rod.Try(func() {
			fmt.Println(page.MustElement("a").MustHTML()) // use "Must" prefixed functions
		})
		check(err)
	}

	// The block below is better for production code. It's the standard way to handle errors.
	// Usually, this style is more consistent and precise.
	{
		el, err := page.Element("a")
		if err != nil {
			check(err)
			return
		}
		html, err := el.HTML()
		if err != nil {
			check(err)
			return
		}
		fmt.Println(html)
	}
}
Example (Eval_reuse_remote_object)

Shows how to share a remote object reference between two Eval.

package main

import (
	"fmt"

	"github.com/rah-0/rod"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage()

	fn := page.MustEvaluate(rod.Eval(`() => Math.random`).ByObject())

	res := page.MustEval(`f => f()`, fn)

	// print a random number
	fmt.Println(res.Num())
}
Example (Handle_events)

Shows how to listen for events.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_, _ = fmt.Fprint(w, `<!doctype html><title>Event example</title>`)
	}))
	defer server.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	browser := rod.New().Context(ctx).NoDefaultDevice().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage()

	// Listen until the first console log, then collect the listener's error.
	waitConsole := page.EachEvent(rod.On(func(e *proto.RuntimeConsoleAPICalled, _ proto.TargetSessionID) bool {
		if e.Type == proto.RuntimeConsoleAPICalledTypeLog {
			fmt.Println(page.MustObjectsToJSON(e.Args))
			return true
		}
		return false
	}))
	done := make(chan error, 1)
	go func() { done <- waitConsole() }()

	wait := page.WaitEvent(&proto.PageLoadEventFired{})
	page.MustNavigate(server.URL)
	utils.E(wait())

	// EachEvent allows us to achieve the same functionality as above.
	if false {
		// Subscribe events before they happen, run the "wait()" to start consuming
		// the events. We can return an optional stop signal to unsubscribe events.
		wait := page.EachEvent(rod.On(func(_ *proto.PageLoadEventFired, _ proto.TargetSessionID) (stop bool) {
			return true
		}))
		page.MustNavigate(server.URL)
		utils.E(wait())
	}

	// Or the for-loop style to handle events to do the same thing above.
	if false {
		// Raw event subscriptions need their protocol domain enabled explicitly.
		utils.E(proto.PageEnable{}.Call(page))
		eventPage, cancel := page.WithCancel()
		defer cancel()
		events := eventPage.Event()
		page.MustNavigate(server.URL)

		for msg := range events {
			e := proto.PageLoadEventFired{}
			if msg.Load(&e) {
				break
			}
		}
		cancel()
		utils.E(proto.PageDisable{}.Call(page))
	}

	page.MustEval(`() => console.log("hello", "world")`)

	utils.E(<-done)

}
Output:
[hello world]
Example (Hijack_requests)

Shows how to intercept requests and modify both the request and the response. The entire process of hijacking one request:

browser --req-> rod ---> server ---> rod --res-> browser

The --req-> and --res-> are the parts that can be modified.

package main

import (
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/app.js" {
			w.Header().Set("Content-Type", "application/javascript")
			_, _ = fmt.Fprint(w, `document.title = "before"`)
			return
		}
		_, _ = fmt.Fprint(w, `<script src="/app.js"></script>`)
	}))
	defer server.Close()

	browser := rod.New().MustConnect()
	defer browser.MustClose()

	router := browser.HijackRequests()

	router.MustAdd("*.js", func(ctx *rod.Hijack) {
		// Here we update the request's header. Rod gives functionality to
		// change or update all parts of the request. Refer to the documentation
		// for more information.
		ctx.Request.Req().Header.Set("My-Header", "test")

		// LoadResponse runs the default request to the destination of the request.
		// Not calling this will require you to mock the entire response.
		// This can be done with the SetXxx (Status, Header, Body) functions on the
		// ctx.Response struct.
		ctx.MustLoadResponse()

		// Here we append some code to every js file.
		// The code will update the document title to "hi"
		ctx.Response.SetBody(ctx.Response.Body() + "\n document.title = 'hi' ")
	})

	done := make(chan error, 1)
	go func() { done <- router.Run() }()
	defer func() {
		stopErr := router.Stop()
		runErr := <-done
		utils.E(errors.Join(stopErr, runErr))
	}()

	browser.MustPage(server.URL).MustWait(`() => document.title === 'hi'`)

	fmt.Println("done")

}
Output:
done
Example (Load_extension)
package main

import (
	"fmt"
	"path/filepath"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/launcher"
)

func main() {
	extPath, _ := filepath.Abs("fixtures/chrome-extension")

	l := launcher.New().
		// Must use abs path for an extension
		Set("load-extension", extPath).
		// Headless mode doesn't support extension yet.
		// Reason: https://bugs.chromium.org/p/chromium/issues/detail?id=706008#c5
		// On Linux, a trusted local launcher can use Launcher.XVFB for a virtual display.
		Headless(false)
	defer func() {
		l.Kill()
		l.Cleanup()
	}()
	u := l.MustLaunch()

	browser := rod.New().ControlURL(u).MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("http://mdn.dev")

	page.MustWait(`() => document.title === 'test-extension'`)

	fmt.Println("ok")

	// Skip
	
Example (Log_cdp_traffic)
package main

import (
	"fmt"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/cdp"
	"github.com/rah-0/rod/lib/launcher"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	l := launcher.New()
	defer func() {
		l.Kill()
		l.Cleanup()
	}()
	u := l.MustLaunch()

	cdp := cdp.New().
		// Here we can customize how to log the requests, responses, and events transferred between Rod and the browser.
		Logger(utils.Log(func(args ...any) {
			switch v := args[0].(type) {
			case *cdp.Request:
				fmt.Printf("id: %d", v.ID)
			}
		})).
		Start(cdp.MustConnectWS(u))

	browser := rod.New().Client(cdp).MustConnect()
	defer browser.MustClose()

	browser.MustPage("http://mdn.dev")
}
Example (Page_pdf)
package main

import (
	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://github.com").MustWaitLoad()

	// simple version
	page.MustPDF("my.pdf")

	// customized version
	pdf, _ := page.PDF(&proto.PagePrintToPDF{
		PaperWidth:  new(8.5),
		PaperHeight: new(float64(11)),
		PageRanges:  "1-3",
	})
	_ = utils.OutputFile("my.pdf", pdf)
}
Example (Page_screenshot)
package main

import (
	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://github.com").MustWaitLoad()

	// simple version
	page.MustScreenshot("my.png")

	// customization version
	img, _ := page.Screenshot(true, &proto.PageCaptureScreenshot{
		Format:  proto.PageCaptureScreenshotFormatJpeg,
		Quality: new(90),
		Clip: &proto.PageViewport{
			X:      0,
			Y:      0,
			Width:  300,
			Height: 200,
			Scale:  1,
		},
		FromSurface: new(true),
	})
	_ = utils.OutputFile("my.jpg", img)
}
Example (Page_scroll_screenshot)
package main

import (
	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
	"github.com/rah-0/rod/lib/utils"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	// capture entire browser viewport, returning jpg with quality=90
	img, err := browser.MustPage("https://desktop.github.com/").MustWaitStable().ScrollScreenshot(&rod.ScrollScreenshotOptions{
		Format:  proto.PageCaptureScreenshotFormatJpeg,
		Quality: new(90),
	})
	if err != nil {
		panic(err)
	}

	_ = utils.OutputFile("my.jpg", img)
}
Example (Race_selectors)

Show how to handle multiple results of an action. Such as when you login a page, the result can be success or wrong password.

package main

import (
	"fmt"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/input"
)

func main() {
	const username = ""
	const password = ""

	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage("https://leetcode.com/accounts/login/")

	page.MustElement("#id_login").MustInput(username)
	page.MustElement("#id_password").MustInput(password).MustType(input.Enter)

	// It will keep retrying until one selector has found a match
	elm := page.Race().Element(".nav-user-icon-base").MustHandle(func(e *rod.Element) {
		// print the username after successful login
		fmt.Println(*e.MustAttribute("title"))
	}).Element("[data-cy=sign-in-error]").MustDo()

	if elm.MustMatches("[data-cy=sign-in-error]") {
		// when wrong username or password
		panic(elm.MustText())
	}
}
Example (States)

Shows how to update the state of the current page. In this example we enable the network domain.

package main

import (
	"fmt"

	"github.com/rah-0/rod"
	"github.com/rah-0/rod/lib/proto"
)

func main() {
	browser := rod.New().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage()

	// LoadState detects whether the network domain is enabled or not.
	fmt.Println(page.LoadState(&proto.NetworkEnable{}))

	_ = proto.NetworkEnable{}.Call(page)

	// Check if the network domain is successfully enabled.
	fmt.Println(page.LoadState(&proto.NetworkEnable{}))

}
Output:
false
true
Example (Wait_for_animation)

Rod uses mouse cursor to simulate clicks, so if a button is moving because of animation, the click may not work as expected. We usually use WaitStable to make sure the target isn't changing anymore.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/rah-0/rod"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	browser := rod.New().Context(ctx).NoDefaultDevice().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage().MustSetDocumentContent(`<!doctype html>
<button id="open">Open dialog</button>
<section id="dialog" hidden style="position: absolute; top: 80px; left: 0">
  <button onclick="this.parentElement.hidden = true">Close</button>
</section>
<script>
document.querySelector("#open").onclick = () => {
  const dialog = document.querySelector("#dialog")
  dialog.hidden = false
  dialog.animate([{transform: "translateX(0)"}, {transform: "translateX(120px)"}],
                 {duration: 400, fill: "forwards"})
}
</script>`)

	page.MustElement("#open").MustClick()

	closeButton := page.MustElementR("#dialog button", "Close")

	// Here, WaitStable will wait until the button's position and size become stable.
	closeButton.MustWaitStable().MustClick().MustWaitInvisible()

	fmt.Println("done")

}
Output:
done
Example (Wait_for_request)

When you want to wait for an ajax request to complete, this example will be useful.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/rah-0/rod"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/suggestions" {
			w.Header().Set("Content-Type", "application/json")
			_, _ = fmt.Fprint(w, `["Common Lisp", "Scheme"]`)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_, _ = fmt.Fprint(w, `<!doctype html>
<input id="search"><ul id="suggestions"></ul>
<script>
document.querySelector("#search").oninput = async event => {
  const response = await fetch("/suggestions?q=" + encodeURIComponent(event.target.value))
  const suggestions = await response.json()
  document.querySelector("#suggestions").replaceChildren(...suggestions.map(text => {
    const item = document.createElement("li")
    item.textContent = text
    return item
  }))
}
</script>`)
	}))
	defer server.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	browser := rod.New().Context(ctx).NoDefaultDevice().MustConnect()
	defer browser.MustClose()

	page := browser.MustPage(server.URL).MustWaitLoad()

	// Start to analyze request events
	wait := page.MustWaitRequestIdle()

	// This will trigger the search ajax request
	page.MustElement("#search").MustInput("lisp")

	// Wait until there's no active requests
	wait()

	// The response supplies both autocomplete suggestions.
	fmt.Println(page.MustElements("#suggestions li").First().MustText())
	fmt.Println(len(page.MustElements("#suggestions li")))

}
Output:
Common Lisp
2

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultLogger = log.New(os.Stdout, "[rod] ", log.LstdFlags)

DefaultLogger for rod.

View Source
var DefaultSleeper = func() utils.Sleeper {
	return utils.BackoffSleeper(100*time.Millisecond, time.Second, nil)
}

DefaultSleeper generates the default sleeper for retry, it uses backoff to grow the interval. The growth looks like:

A(0) = 100ms, A(n) = A(n-1) * random[1.9, 2.1), A(n) < 1s

Why the default is not RequestAnimationFrame or DOM change events is because of if a retry never ends it can easily flood the program. But you can always easily config it into what you want.

View Source
var ErrBrowserDisconnected = errors.New("browser connection closed")

ErrBrowserDisconnected means the browser event stream closed before a wait completed.

View Source
var ErrCleanupTimeout = errors.New("browser cleanup timeout must be positive")

ErrCleanupTimeout indicates an invalid cleanup time budget.

View Source
var ErrDiagnosticsIncomplete = errors.New("rod: incomplete page diagnostics")

ErrDiagnosticsIncomplete means the protocol boundary or cleanup could not finish. The returned snapshot still contains the diagnostics collected so far.

View Source
var ErrDiagnosticsOptions = errors.New("rod: invalid diagnostics options")

ErrDiagnosticsOptions means a diagnostics limit is negative.

View Source
var ErrDownloadCanceled = errors.New("rod: download canceled")

ErrDownloadCanceled indicates that Chrome canceled the selected download.

View Source
var ErrDownloadInProgress = errors.New("rod: a download wait is already active in this browser context")

ErrDownloadInProgress indicates another wait owns download behavior in this context.

View Source
var ErrFrameContextChanged = errors.New("iframe context changed; acquire a new view with Element.Frame")

ErrFrameContextChanged means an iframe document or renderer is no longer available to this page view. Acquire a new view with Element.Frame.

View Source
var ErrLaunchConflict = errors.New("owned launch requires an unconnected browser, a non-nil local launcher, and no ControlURL, Client, or incognito context")

ErrLaunchConflict indicates that configured local launch conflicts with the browser configuration.

Functions

func NotFoundSleeper

func NotFoundSleeper() utils.Sleeper

NotFoundSleeper returns ErrElementNotFound on the first call.

func Try

func Try(fn func()) (err error)

Try try fn with recover, return the panic as rod.ErrTry.

Types

type Browser

type Browser struct {
	// BrowserContextID is the id for incognito window
	BrowserContextID proto.BrowserBrowserContextID
	// contains filtered or unexported fields
}

Browser represents the browser. It doesn't depends on file system, it should work with remote browser seamlessly. To check the command-line defaults you can use to quickly enable options, check here: https://pkg.go.dev/github.com/rah-0/rod/lib/defaults

Example (Pool)

We can use rod.BrowserPool to concurrently control and reuse browsers.

package main

import (
	"fmt"
	"sync"

	"github.com/rah-0/rod"
)

func main() {
	// Create a new browser pool with a limit of 3
	pool := rod.NewBrowserPool(3)
	// Close every pooled browser when the example returns.
	defer pool.Cleanup(func(browser *rod.Browser) {
		browser.MustClose()
	})

	// Create a function that returns a new browser instance
	create := func() *rod.Browser {
		browser := rod.New().MustConnect()
		return browser
	}

	// Explicit Done preserves cleanup if a Must helper panics.
	var wg sync.WaitGroup
	for range 3 {
		wg.Add(1)
		go func() {
			defer wg.Done()

			// Get a browser instance from the pool
			browser := pool.MustGet(create)

			// Put the instance back to the pool after we're done,
			// so the instance can be reused by other goroutines.
			defer pool.Put(browser)

			// Use the browser instance
			page := browser.MustPage("https://www.google.com")
			fmt.Println(page.MustInfo().Title)
		}()
	}

	// Wait for all the goroutines to finish
	wg.Wait()
}

func New

func New() *Browser

New creates a controller. DefaultDevice to emulate is set to devices.LaptopWithMDPIScreen.Landscape(), it will change the default user-agent and can make the actual view area smaller than the browser window on headful mode, you can use Browser.NoDefaultDevice to disable it.

func (*Browser) Call

func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error)

Call implements the proto.Client to call raw cdp interface directly.

func (*Browser) CancelTimeout

func (b *Browser) CancelTimeout() *Browser

CancelTimeout cancels the current timeout context and returns a clone with the parent context.

func (*Browser) Client

func (b *Browser) Client(c CDPClient) *Browser

Client set the cdp client.

func (*Browser) Close

func (b *Browser) Close() error

Close closes the browser. Owned local browsers have a ten-second cleanup budget independent of operation cancellation, including up to five seconds for graceful shutdown. Closing incognito disposes only that context.

func (*Browser) CloseWithTimeout added in v0.120.0

func (b *Browser) CloseWithTimeout(timeout time.Duration) error

CloseWithTimeout closes using a positive total budget independent of the operation context. Owned processes get up to half the budget (at most five seconds) to close gracefully, then are terminated and their cleanup is checked in the remaining time. A timeout retains process ownership for later cleanup. An incognito browser disposes only its context; an attached browser has no local process to terminate. Custom clients must honor request cancellation.

func (*Browser) Connect

func (b *Browser) Connect() error

Connect to the browser and start to control it. If it fails to connect, it tries to launch an installed local browser. A browser launched by Connect is stopped when this context is canceled or its connection ends. Context clones created after Connect do not own its lifetime.

func (*Browser) Context

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

Context returns a clone with the specified ctx for chained sub-operations.

func (*Browser) ControlURL

func (b *Browser) ControlURL(url string) *Browser

ControlURL set the url to remote control browser.

func (*Browser) DefaultDevice

func (b *Browser) DefaultDevice(d devices.Device) *Browser

DefaultDevice sets the default device for new page to emulate in the future. Default is devices.LaptopWithMDPIScreen. Set it to devices.Clear to disable it.

func (*Browser) DisableDomain

func (b *Browser) DisableDomain(sessionID proto.TargetSessionID, req proto.Request) (func() error, error)

DisableDomain temporarily disables a domain, including active automatic owners. Its idempotent restore function reapplies the previous enabled configuration using an independent five-second cleanup budget. Failed setup attempts restore that configuration before returning the setup and any restoration errors.

func (*Browser) EachEvent

func (b *Browser) EachEvent(handlers ...EventHandler) func() error

EachEvent subscribes to the given handlers across all browser sessions. Handlers run in message order; returning true stops the wait. The returned wait reports domain setup, cancellation, connection termination, and cleanup errors.

func (*Browser) EnableDomain

func (b *Browser) EnableDomain(sessionID proto.TargetSessionID, req proto.Request) (func() error, error)

EnableDomain enables a domain until its idempotent restore function is called. Overlapping users share ownership; the last restores the original state. Domains explicitly enabled before the first owner remain enabled. Restoration uses an independent five-second cleanup budget.

func (*Browser) Event

func (b *Browser) Event() <-chan *Message

Event of the browser.

func (*Browser) GetContext

func (b *Browser) GetContext() context.Context

GetContext of current instance.

func (*Browser) GetCookies

func (b *Browser) GetCookies() ([]*proto.NetworkCookie, error)

GetCookies from the browser.

func (*Browser) HandleAuth

func (b *Browser) HandleAuth(username, password string) func() error

HandleAuth for the next basic HTTP authentication. It will prevent the popup that requires user to input user name and password. Call the returned wait function to handle authentication and restore the previous Fetch configuration. It returns setup, wait, and cleanup errors. Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Authentication

func (*Browser) HijackRequests

func (b *Browser) HijackRequests() *HijackRouter

HijackRequests same as Page.HijackRequests, but can intercept requests of the entire browser.

func (*Browser) IgnoreCertErrors

func (b *Browser) IgnoreCertErrors(enable bool) error

IgnoreCertErrors switch. If enabled, all certificate errors will be ignored.

func (*Browser) Incognito

func (b *Browser) Incognito() (*Browser, error)

Incognito creates a new incognito browser.

func (*Browser) Launch added in v0.120.0

func (b *Browser) Launch(l *launcher.Launcher) (err error)

Launch starts an unlaunched, configured local launcher, connects this Browser, and owns that new process until Close, owner-context cancellation, or disconnect. ControlURL, Client, an existing connection, and incognito contexts conflict with this operation. An occupied debugging port is never adopted. The launcher's output tail is included in startup and connection errors.

func (*Browser) LoadState

func (b *Browser) LoadState(sessionID proto.TargetSessionID, method proto.Request) (has bool)

LoadState into the method, sessionID can be empty.

func (*Browser) Logger

func (b *Browser) Logger(l utils.Logger) *Browser

Logger overrides the default log functions for tracing.

func (*Browser) Monitor

func (b *Browser) Monitor(url string) *Browser

Monitor address to listen if not empty. Shortcut for Browser.ServeMonitor. The monitor has no authentication, so keep it on loopback or protect it with a trusted authenticated proxy.

func (*Browser) MustClose

func (b *Browser) MustClose()

MustClose is similar to Browser.Close.

func (*Browser) MustConnect

func (b *Browser) MustConnect() *Browser

MustConnect is similar to Browser.Connect.

func (*Browser) MustGetCookies

func (b *Browser) MustGetCookies() []*proto.NetworkCookie

MustGetCookies is similar to Browser.GetCookies.

func (*Browser) MustHandleAuth

func (b *Browser) MustHandleAuth(username, password string) (wait func())

MustHandleAuth is similar to Browser.HandleAuth.

func (*Browser) MustIgnoreCertErrors

func (b *Browser) MustIgnoreCertErrors(enable bool) *Browser

MustIgnoreCertErrors is similar to Browser.IgnoreCertErrors.

func (*Browser) MustIncognito

func (b *Browser) MustIncognito() *Browser

MustIncognito is similar to Browser.Incognito.

func (*Browser) MustPage

func (b *Browser) MustPage(url ...string) *Page

MustPage is similar to Browser.Page. The url list will be joined by "/".

func (*Browser) MustPageFromTargetID

func (b *Browser) MustPageFromTargetID(targetID proto.TargetTargetID) *Page

MustPageFromTargetID is similar to [Browser.PageFromTargetID].

func (*Browser) MustPages

func (b *Browser) MustPages() Pages

MustPages is similar to Browser.Pages.

func (*Browser) MustSetCookies

func (b *Browser) MustSetCookies(cookies ...*proto.NetworkCookie) *Browser

MustSetCookies is similar to Browser.SetCookies. If the len(cookies) is 0 it will clear all the cookies.

func (*Browser) MustVersion

func (b *Browser) MustVersion() *proto.BrowserGetVersionResult

MustVersion is similar to Browser.Version.

func (*Browser) MustWaitDownload

func (b *Browser) MustWaitDownload() func() []byte

MustWaitDownload is similar to Browser.WaitDownload. It will read the file into bytes then remove the file.

func (*Browser) NoDefaultDevice

func (b *Browser) NoDefaultDevice() *Browser

NoDefaultDevice is the same as Browser.DefaultDevice(devices.Clear).

func (*Browser) Page

func (b *Browser) Page(opts proto.TargetCreateTarget) (p *Page, err error)

Page creates a new browser tab. If opts.URL is empty, the default target will be "about:blank".

func (*Browser) PageFromSession

func (b *Browser) PageFromSession(sessionID proto.TargetSessionID) *Page

PageFromSession is used for low-level debugging. Its requests use the supplied browser context and, for known sessions, their shared connection lifetime.

func (*Browser) PageFromTarget

func (b *Browser) PageFromTarget(targetID proto.TargetTargetID) (*Page, error)

PageFromTarget attaches once per target and returns a view using this Browser's operation context. Canceling a view does not cancel the shared page session.

func (*Browser) Pages

func (b *Browser) Pages() (Pages, error)

Pages retrieves visible pages. An incognito Browser returns only pages from its own browser context; the root Browser can enumerate every context.

func (*Browser) RemoveState

func (b *Browser) RemoveState(key any)

RemoveState a state.

func (*Browser) ServeMonitor

func (b *Browser) ServeMonitor(host string) string

ServeMonitor starts the monitor server. The reason why not to use "chrome://inspect/#devices" is one target cannot be driven by multiple controllers. The monitor has no authentication. Keep host on loopback or protect it with a trusted authenticated proxy.

func (*Browser) SetCookies

func (b *Browser) SetCookies(cookies []*proto.NetworkCookieParam) error

SetCookies to the browser. If the cookies is nil it will clear all the cookies.

func (*Browser) Sleeper

func (b *Browser) Sleeper(sleeper func() utils.Sleeper) *Browser

Sleeper returns a clone with the specified sleeper for chained sub-operations.

func (*Browser) SlowMotion

func (b *Browser) SlowMotion(delay time.Duration) *Browser

SlowMotion set the delay for each control action, such as the simulation of the human inputs.

func (*Browser) Timeout

func (b *Browser) Timeout(d time.Duration) *Browser

Timeout returns a clone with the specified total timeout of all chained sub-operations.

func (*Browser) Trace

func (b *Browser) Trace(enable bool) *Browser

Trace enables/disables the visual tracing of the input actions on the page.

func (*Browser) Version

func (b *Browser) Version() (*proto.BrowserGetVersionResult, error)

Version info of the browser.

func (*Browser) WaitDownload

func (b *Browser) WaitDownload(dir string) (func() (*proto.BrowserDownloadWillBegin, error), error)

WaitDownload configures downloads and subscribes before returning. Invoke its single-use wait after triggering a download; it returns the first download in this browser context when that GUID completes, or an error on cancellation. Files are saved as filepath.Join(dir, info.GUID). Only one wait may configure a browser context at once. Both completion and context cancellation restore the previous behavior, using an independent five-second cleanup budget. Browser download events remain enabled until the last concurrent context waiter stops.

func (*Browser) WaitEvent

func (b *Browser) WaitEvent[E proto.Event](out *E) func() error

WaitEvent loads the next matching event into out. E is a concrete protocol event type.

func (*Browser) WithCancel

func (b *Browser) WithCancel() (*Browser, func())

WithCancel returns a clone with a context cancel function.

func (*Browser) WithPanic

func (b *Browser) WithPanic(fail func(any)) *Browser

WithPanic returns a browser clone with the specified panic function. The fail must stop the current goroutine's execution immediately, such as use runtime.Goexit or panic inside it.

type CDPClient

type CDPClient interface {
	Event() <-chan *cdp.Event
	Call(ctx context.Context, sessionID, method string, params any) ([]byte, error)
}

CDPClient is usually used to make rod side-effect free. Such as proxy all IO of rod.

type ConsoleMessage added in v0.120.0

type ConsoleMessage struct {
	Type proto.RuntimeConsoleAPICalledType
	Text string
	DiagnosticLocation
}

ConsoleMessage is rendered only from the console event payload.

type CoveredError

type CoveredError struct {
	*Element
}

CoveredError error.

func (*CoveredError) Error

func (e *CoveredError) Error() string

Error ...

func (*CoveredError) Is

func (e *CoveredError) Is(err error) bool

Is interface.

func (*CoveredError) Unwrap

func (e *CoveredError) Unwrap() error

Unwrap ...

type DiagnosticLocation added in v0.120.0

type DiagnosticLocation struct {
	URL    string
	Line   int
	Column int
}

DiagnosticLocation uses one-based coordinates; zero means unavailable.

type DiagnosticsOptions added in v0.120.0

type DiagnosticsOptions struct {
	// MaxRecords retains the first 1000 records of each kind by default.
	MaxRecords int
	// MaxTextBytes bounds each retained text field, including rendered arguments.
	// The default is 4096 bytes; truncated text ends with an ellipsis.
	MaxTextBytes int
	// MaxRequests bounds in-flight request tracking (default 1000). New requests
	// beyond the limit are not tracked until a slot becomes available.
	MaxRequests int
	// MaxPreviewDepth bounds nested object previews (default 3).
	MaxPreviewDepth int
	// StopTimeout bounds draining and, separately, cleanup (default 5 seconds).
	StopTimeout time.Duration
}

DiagnosticsOptions bounds collection. Zero fields select the documented defaults.

type DiagnosticsSnapshot added in v0.120.0

type DiagnosticsSnapshot struct {
	Console                 []ConsoleMessage
	PageErrors              []PageError
	ResourceFailures        []ResourceFailure
	DroppedConsole          int
	DroppedPageErrors       int
	DroppedResourceFailures int
	DroppedRequests         int
}

DiagnosticsSnapshot owns its slices and is safe to modify. Each category keeps its first MaxRecords entries; Dropped counts later entries. Revoked exceptions free their retained slot. DroppedRequests counts denied tracking admissions.

type Element

type Element struct {
	Object *proto.RuntimeRemoteObject
	// contains filtered or unexported fields
}

Element represents the DOM element.

func (*Element) Attribute

func (el *Element) Attribute(name string) (*string, error)

Attribute of the DOM object. Attribute vs Property: https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html

func (*Element) BackgroundImage

func (el *Element) BackgroundImage() ([]byte, error)

BackgroundImage returns the css background-image of the element.

func (*Element) Blur

func (el *Element) Blur() error

Blur removes focus from the element.

func (*Element) Call

func (el *Element) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error)

Call implements the proto.Client.

func (*Element) CancelTimeout

func (el *Element) CancelTimeout() *Element

CancelTimeout cancels the current timeout context and returns a clone with the parent context.

func (*Element) CanvasToImage

func (el *Element) CanvasToImage(format string, quality float64) ([]byte, error)

CanvasToImage get image data of a canvas. The default format is image/png. The default quality is 0.92. doc: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL

func (*Element) Click

func (el *Element) Click(button proto.InputMouseButton, clickCount int) error

Click will press then release the button just like a human. Before the action, it will try to scroll to the element, hover the mouse over it, wait until the it's interactable and enabled.

func (*Element) ContainsElement

func (el *Element) ContainsElement(target *Element) (bool, error)

ContainsElement check if the target is equal or inside the element.

func (*Element) Context

func (el *Element) Context(ctx context.Context) *Element

Context returns a clone with the specified ctx for chained sub-operations.

func (*Element) Describe

func (el *Element) Describe(depth int, pierce bool) (*proto.DOMNode, error)

Describe the current element. The depth is the maximum depth at which children should be retrieved, defaults to 1, use -1 for the entire subtree or provide an integer larger than 0. The pierce decides whether or not iframes and shadow roots should be traversed when returning the subtree. The returned proto.DOMNode.NodeID will always be empty, because NodeID is not stable (when proto.DOMDocumentUpdated is fired all NodeID on the page will be reassigned to another value) we don't recommend using the NodeID, instead, use the proto.DOMBackendNodeID to identify the element.

func (*Element) Disabled

func (el *Element) Disabled() (bool, error)

Disabled checks if the element is disabled.

func (*Element) Element

func (el *Element) Element(selector string) (*Element, error)

Element returns the first child that matches the css selector.

func (*Element) ElementByJS

func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error)

ElementByJS returns the element from the return value of the js.

func (*Element) ElementR

func (el *Element) ElementR(selector, jsRegex string) (*Element, error)

ElementR returns the first child element that matches the css selector and its text matches the jsRegex.

func (*Element) ElementX

func (el *Element) ElementX(xPath string) (*Element, error)

ElementX returns the first child that matches the XPath selector.

func (*Element) Elements

func (el *Element) Elements(selector string) (Elements, error)

Elements returns all elements that match the css selector.

func (*Element) ElementsByJS

func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error)

ElementsByJS returns the elements from the return value of the js.

func (*Element) ElementsX

func (el *Element) ElementsX(xpath string) (Elements, error)

ElementsX returns all elements that match the XPath selector.

func (*Element) Equal

func (el *Element) Equal(elm *Element) (bool, error)

Equal checks if the two elements are equal.

func (*Element) Eval

func (el *Element) Eval(js string, params ...any) (*proto.RuntimeRemoteObject, error)

Eval is a shortcut for Element.Evaluate with AwaitPromise, ByValue and AutoExp set to true.

func (*Element) Evaluate

func (el *Element) Evaluate(opts *EvalOptions) (*proto.RuntimeRemoteObject, error)

Evaluate is just a shortcut of Page.Evaluate with This set to current element.

func (*Element) Focus

func (el *Element) Focus() error

Focus sets focus on the specified element. Before the action, it will try to scroll to the element.

func (*Element) Frame

func (el *Element) Frame() (*Page, error)

Frame creates a page view for this iframe, attaching its renderer session when necessary. The view uses the element's context. If navigation moves the frame to another renderer, acquire a new view with Frame; the old view retains its original session and reports an error once that session or document is gone.

func (*Element) GetContext

func (el *Element) GetContext() context.Context

GetContext of current instance.

func (*Element) GetSessionID

func (el *Element) GetSessionID() proto.TargetSessionID

GetSessionID interface.

func (*Element) GetXPath

func (el *Element) GetXPath(optimized bool) (string, error)

GetXPath returns the xpath of the element.

func (*Element) HTML

func (el *Element) HTML() (string, error)

HTML of the element.

func (*Element) Has

func (el *Element) Has(selector string) (bool, *Element, error)

Has an element that matches the css selector.

func (*Element) HasR

func (el *Element) HasR(selector, jsRegex string) (bool, *Element, error)

HasR returns true if a child element that matches the css selector and its text matches the jsRegex.

func (*Element) HasX

func (el *Element) HasX(selector string) (bool, *Element, error)

HasX an element that matches the XPath selector.

func (*Element) Hover

func (el *Element) Hover() error

Hover the mouse over the center of the element. Before the action, it will try to scroll to the element and wait until it's interactable.

func (*Element) Input

func (el *Element) Input(text string) error

Input focuses on the element and input text to it. Before the action, it will scroll to the element, wait until it's visible, enabled and writable. To empty the input you can use something like

el.SelectAllText().MustInput("")

func (*Element) InputColor

func (el *Element) InputColor(color string) error

InputColor focuses on the element and inputs a color string to it. Before the action, it will scroll to the element, wait until it's visible, enabled and writable.

func (*Element) InputTime

func (el *Element) InputTime(t time.Time) error

InputTime focuses on the element and input time to it. Before the action, it will scroll to the element, wait until it's visible, enabled and writable. It will wait until the element is visible, enabled and writable.

func (*Element) Interactable

func (el *Element) Interactable() (pt *proto.Point, err error)

Interactable checks if the element is interactable with cursor. The cursor can be mouse, finger, stylus, etc. If not interactable err will be ErrNotInteractable, such as when covered by a modal,.

func (*Element) KeyActions

func (el *Element) KeyActions() (*KeyActions, error)

KeyActions is similar with Page.KeyActions. Before the action, it will try to scroll to the element and focus on it.

func (*Element) Matches

func (el *Element) Matches(selector string) (bool, error)

Matches checks if the element can be selected by the css selector.

func (*Element) MoveMouseOut

func (el *Element) MoveMouseOut() error

MoveMouseOut of the current element.

func (*Element) MustAttribute

func (el *Element) MustAttribute(name string) *string

MustAttribute is similar to Element.Attribute.

func (*Element) MustBackgroundImage

func (el *Element) MustBackgroundImage() []byte

MustBackgroundImage is similar to Element.BackgroundImage.

func (*Element) MustBlur

func (el *Element) MustBlur() *Element

MustBlur is similar to Element.Blur.

func (*Element) MustCanvasToImage

func (el *Element) MustCanvasToImage() []byte

MustCanvasToImage is similar to Element.CanvasToImage.

func (*Element) MustClick

func (el *Element) MustClick() *Element

MustClick is similar to Element.Click.

func (*Element) MustContainsElement

func (el *Element) MustContainsElement(target *Element) bool

MustContainsElement is similar to Element.ContainsElement.

func (*Element) MustDescribe

func (el *Element) MustDescribe() *proto.DOMNode

MustDescribe is similar to Element.Describe.

func (*Element) MustDisabled

func (el *Element) MustDisabled() bool

MustDisabled is similar to Element.Disabled.

func (*Element) MustDoubleClick

func (el *Element) MustDoubleClick() *Element

MustDoubleClick is similar to Element.Click.

func (*Element) MustElement

func (el *Element) MustElement(selector string) *Element

MustElement is similar to Element.Element.

func (*Element) MustElementByJS

func (el *Element) MustElementByJS(js string, params ...any) *Element

MustElementByJS is similar to Element.ElementByJS.

func (*Element) MustElementR

func (el *Element) MustElementR(selector, regex string) *Element

MustElementR is similar to Element.ElementR.

func (*Element) MustElementX

func (el *Element) MustElementX(xpath string) *Element

MustElementX is similar to Element.ElementX.

func (*Element) MustElements

func (el *Element) MustElements(selector string) Elements

MustElements is similar to Element.Elements.

func (*Element) MustElementsByJS

func (el *Element) MustElementsByJS(js string, params ...any) Elements

MustElementsByJS is similar to Element.ElementsByJS.

func (*Element) MustElementsX

func (el *Element) MustElementsX(xpath string) Elements

MustElementsX is similar to Element.ElementsX.

func (*Element) MustEqual

func (el *Element) MustEqual(elm *Element) bool

MustEqual is similar to Element.Equal.

func (*Element) MustEval

func (el *Element) MustEval(js string, params ...any) jsonvalue.Value

MustEval is similar to Element.Eval.

func (*Element) MustFocus

func (el *Element) MustFocus() *Element

MustFocus is similar to Element.Focus.

func (*Element) MustFrame

func (el *Element) MustFrame() *Page

MustFrame is similar to Element.Frame.

func (*Element) MustGetXPath

func (el *Element) MustGetXPath(optimized bool) string

MustGetXPath is similar to Element.GetXPath.

func (*Element) MustHTML

func (el *Element) MustHTML() string

MustHTML is similar to Element.HTML.

func (*Element) MustHas

func (el *Element) MustHas(selector string) bool

MustHas is similar to Element.Has.

func (*Element) MustHasR

func (el *Element) MustHasR(selector, regex string) bool

MustHasR is similar to Element.HasR.

func (*Element) MustHasX

func (el *Element) MustHasX(selector string) bool

MustHasX is similar to Element.HasX.

func (*Element) MustHover

func (el *Element) MustHover() *Element

MustHover is similar to Element.Hover.

func (*Element) MustInput

func (el *Element) MustInput(text string) *Element

MustInput is similar to Element.Input.

func (*Element) MustInputColor

func (el *Element) MustInputColor(color string) *Element

MustInputColor is similar to Element.InputColor.

func (*Element) MustInputTime

func (el *Element) MustInputTime(t time.Time) *Element

MustInputTime is similar to Element.Input.

func (*Element) MustInteractable

func (el *Element) MustInteractable() bool

MustInteractable is similar to Element.Interactable.

func (*Element) MustKeyActions

func (el *Element) MustKeyActions() *KeyActions

MustKeyActions is similar to Element.KeyActions.

func (*Element) MustMatches

func (el *Element) MustMatches(selector string) bool

MustMatches is similar to Element.Matches.

func (*Element) MustMoveMouseOut

func (el *Element) MustMoveMouseOut() *Element

MustMoveMouseOut is similar to Element.MoveMouseOut.

func (*Element) MustNext

func (el *Element) MustNext() *Element

MustNext is similar to Element.Next.

func (*Element) MustParent

func (el *Element) MustParent() *Element

MustParent is similar to Element.Parent.

func (*Element) MustParents

func (el *Element) MustParents(selector string) Elements

MustParents is similar to Element.Parents.

func (*Element) MustPrevious

func (el *Element) MustPrevious() *Element

MustPrevious is similar to Element.Previous.

func (*Element) MustProperty

func (el *Element) MustProperty(name string) jsonvalue.Value

MustProperty is similar to Element.Property.

func (*Element) MustRelease

func (el *Element) MustRelease()

MustRelease is similar to Element.Release.

func (*Element) MustRemove

func (el *Element) MustRemove()

MustRemove is similar to Element.Remove.

func (*Element) MustResource

func (el *Element) MustResource() []byte

MustResource is similar to Element.Resource.

func (*Element) MustScreenshot

func (el *Element) MustScreenshot(toFile ...string) []byte

MustScreenshot is similar to Element.Screenshot.

func (*Element) MustScrollIntoView

func (el *Element) MustScrollIntoView() *Element

MustScrollIntoView is similar to Element.ScrollIntoView.

func (*Element) MustSelect

func (el *Element) MustSelect(selectors ...string) *Element

MustSelect is similar to Element.Select.

func (*Element) MustSelectAllText

func (el *Element) MustSelectAllText() *Element

MustSelectAllText is similar to Element.SelectAllText.

func (*Element) MustSelectText

func (el *Element) MustSelectText(regex string) *Element

MustSelectText is similar to Element.SelectText.

func (*Element) MustSetFiles

func (el *Element) MustSetFiles(paths ...string) *Element

MustSetFiles is similar to Element.SetFiles.

func (*Element) MustShadowRoot

func (el *Element) MustShadowRoot() *Element

MustShadowRoot is similar to Element.ShadowRoot.

func (*Element) MustShape

func (el *Element) MustShape() *proto.DOMGetContentQuadsResult

MustShape is similar to Element.Shape.

func (*Element) MustTap

func (el *Element) MustTap() *Element

MustTap is similar to Element.Tap.

func (*Element) MustText

func (el *Element) MustText() string

MustText is similar to Element.Text.

func (*Element) MustType

func (el *Element) MustType(keys ...input.Key) *Element

MustType is similar to Element.Type.

func (*Element) MustVisible

func (el *Element) MustVisible() bool

MustVisible is similar to Element.Visible.

func (*Element) MustWait

func (el *Element) MustWait(js string, params ...any) *Element

MustWait is similar to Element.Wait.

func (*Element) MustWaitEnabled

func (el *Element) MustWaitEnabled() *Element

MustWaitEnabled is similar to Element.WaitEnabled.

func (*Element) MustWaitInteractable

func (el *Element) MustWaitInteractable() *Element

MustWaitInteractable is similar to Element.WaitInteractable.

func (*Element) MustWaitInvisible

func (el *Element) MustWaitInvisible() *Element

MustWaitInvisible is similar to Element.WaitInvisible..

func (*Element) MustWaitLoad

func (el *Element) MustWaitLoad() *Element

MustWaitLoad is similar to Element.WaitLoad.

func (*Element) MustWaitStable

func (el *Element) MustWaitStable() *Element

MustWaitStable is similar to Element.WaitStable.

func (*Element) MustWaitVisible

func (el *Element) MustWaitVisible() *Element

MustWaitVisible is similar to Element.WaitVisible.

func (*Element) MustWaitWritable

func (el *Element) MustWaitWritable() *Element

MustWaitWritable is similar to Element.WaitWritable.

func (*Element) Next

func (el *Element) Next() (*Element, error)

Next returns the next sibling element in the DOM tree.

func (*Element) Overlay

func (el *Element) Overlay(msg string) (removeOverlay func())

Overlay msg on the element.

func (*Element) Page

func (el *Element) Page() *Page

Page of the element.

func (*Element) Parent

func (el *Element) Parent() (*Element, error)

Parent returns the parent element in the DOM tree.

func (*Element) Parents

func (el *Element) Parents(selector string) (Elements, error)

Parents that match the selector.

func (*Element) Previous

func (el *Element) Previous() (*Element, error)

Previous returns the previous sibling element in the DOM tree.

func (*Element) Property

func (el *Element) Property(name string) (jsonvalue.Value, error)

Property of the DOM object. Property vs Attribute: https://stackoverflow.com/questions/6003819/what-is-the-difference-between-properties-and-attributes-in-html

func (*Element) Release

func (el *Element) Release() error

Release is a shortcut for Page.Release current element.

func (*Element) Remove

func (el *Element) Remove() error

Remove the element from the page.

func (*Element) Resource

func (el *Element) Resource() ([]byte, error)

Resource returns the "src" content of current element. Such as the jpg of <img src="a.jpg">.

func (*Element) Screenshot

func (el *Element) Screenshot(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error)

Screenshot captures the element's transformed bounds. Bounds round outward to device-independent pixel edges; bitmap resolution follows the browser scale.

func (*Element) ScrollIntoView

func (el *Element) ScrollIntoView() error

ScrollIntoView scrolls the current element into the visible area of the browser window if it's not already within the visible area.

func (*Element) Select

func (el *Element) Select(selectors []string, selected bool, t SelectorType) error

Select the children option elements that match the selectors. Before the action, it will scroll to the element, wait until it's visible. If no option matches the selectors, it will return [ErrElementNotFound].

func (*Element) SelectAllText

func (el *Element) SelectAllText() error

SelectAllText selects all text Before the action, it will try to scroll to the element and focus on it.

func (*Element) SelectText

func (el *Element) SelectText(regex string) error

SelectText selects the text that matches the regular expression. Before the action, it will try to scroll to the element and focus on it.

func (*Element) SetFiles

func (el *Element) SetFiles(paths []string) error

SetFiles of the current file input element.

func (*Element) ShadowRoot

func (el *Element) ShadowRoot() (*Element, error)

ShadowRoot returns the shadow root of this element.

func (*Element) Shape

func (el *Element) Shape() (*proto.DOMGetContentQuadsResult, error)

Shape of the DOM element content. The shape is a group of 4-sides polygons. A 4-sides polygon is not necessary a rectangle. 4-sides polygons can be apart from each other. For example, we use 2 4-sides polygons to describe the shape below:

  ____________          ____________
 /        ___/    =    /___________/    +     _________
/________/                                   /________/

func (*Element) Sleeper

func (el *Element) Sleeper(sleeper func() utils.Sleeper) *Element

Sleeper returns a clone with the specified sleeper for chained sub-operations.

func (*Element) String

func (el *Element) String() string

String interface.

func (*Element) Tap

func (el *Element) Tap() error

Tap will scroll to the button and tap it just like a human. Before the action, it will try to scroll to the element and wait until it's interactable and enabled.

func (*Element) Text

func (el *Element) Text() (string, error)

Text that the element displays.

func (*Element) Timeout

func (el *Element) Timeout(d time.Duration) *Element

Timeout returns a clone with the specified total timeout of all chained sub-operations.

func (*Element) Type

func (el *Element) Type(keys ...input.Key) error

Type is similar with Keyboard.Type. Before the action, it will try to scroll to the element and focus on it.

func (*Element) Visible

func (el *Element) Visible() (bool, error)

Visible returns true if the element is visible on the page.

func (*Element) Wait

func (el *Element) Wait(opts *EvalOptions) error

Wait until the js returns true.

func (*Element) WaitEnabled

func (el *Element) WaitEnabled() error

WaitEnabled until the element is not disabled. Doc for disabled: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/disabled

func (*Element) WaitInteractable

func (el *Element) WaitInteractable() (pt *proto.Point, err error)

WaitInteractable waits for the element to be interactable. It will try to scroll to the element on each try.

func (*Element) WaitInvisible

func (el *Element) WaitInvisible() error

WaitInvisible until the element invisible.

func (*Element) WaitLoad

func (el *Element) WaitLoad() error

WaitLoad for element like <img>.

func (*Element) WaitStable

func (el *Element) WaitStable(d time.Duration) error

WaitStable waits until no shape or position change for d duration. Be careful, d is not the max wait timeout, it's the least stable time. If you want to set a timeout you can use the Element.Timeout function.

func (*Element) WaitStableRAF

func (el *Element) WaitStableRAF() error

WaitStableRAF waits until no shape or position change for 2 consecutive animation frames. If you want to wait animation that is triggered by JS not CSS, you'd better use Element.WaitStable. About animation frame: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

func (*Element) WaitVisible

func (el *Element) WaitVisible() error

WaitVisible until the element is visible.

func (*Element) WaitWritable

func (el *Element) WaitWritable() error

WaitWritable until the element is not readonly. Doc for readonly: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Attributes/readonly

func (*Element) WithCancel

func (el *Element) WithCancel() (*Element, func())

WithCancel returns a clone with a context cancel function.

func (*Element) WithPanic

func (el *Element) WithPanic(fail func(any)) *Element

WithPanic returns an element clone with the specified panic function. The fail must stop the current goroutine's execution immediately, such as use runtime.Goexit or panic inside it.

type ElementNotFoundError

type ElementNotFoundError struct{}

ElementNotFoundError error.

func (*ElementNotFoundError) Error

func (e *ElementNotFoundError) Error() string

type Elements

type Elements []*Element

Elements provides some helpers to deal with element list.

func (Elements) Empty

func (els Elements) Empty() bool

Empty returns true if the list is empty.

func (Elements) First

func (els Elements) First() *Element

First returns the first element, if the list is empty returns nil.

func (Elements) Last

func (els Elements) Last() *Element

Last returns the last element, if the list is empty returns nil.

type EvalError

type EvalError struct {
	*proto.RuntimeExceptionDetails
}

EvalError error.

func (*EvalError) Error

func (e *EvalError) Error() string

func (*EvalError) Is

func (e *EvalError) Is(err error) bool

Is interface.

type EvalOptions

type EvalOptions struct {
	// If enabled the eval result will be a plain JSON value.
	// If disabled the eval result will be a reference of a remote js object.
	ByValue bool

	AwaitPromise bool

	// ThisObj represents the "this" object in the JS
	ThisObj *proto.RuntimeRemoteObject

	// JS function definition to execute.
	JS string

	// JSArgs represents the arguments that will be passed to JS.
	// If an argument is [*proto.RuntimeRemoteObject] type, the corresponding remote object will be used.
	// Or it will be passed as a plain JSON value.
	// When an arg in the args is a *js.Function, the arg will be cached on the page's js context.
	// When the arg.Name exists in the page's cache, it reuse the cache without sending
	// the definition to the browser again.
	// Useful when you need to eval a huge js expression many times.
	JSArgs []any

	// Whether execution should be treated as initiated by user in the UI.
	UserGesture bool
}

EvalOptions for Page.Evaluate.

func Eval

func Eval(js string, args ...any) *EvalOptions

Eval creates a EvalOptions with ByValue set to true.

func (*EvalOptions) ByObject

func (e *EvalOptions) ByObject() *EvalOptions

ByObject disables ByValue.

func (*EvalOptions) ByPromise

func (e *EvalOptions) ByPromise() *EvalOptions

ByPromise enables AwaitPromise.

func (*EvalOptions) ByUser

func (e *EvalOptions) ByUser() *EvalOptions

ByUser enables UserGesture.

func (*EvalOptions) String

func (e *EvalOptions) String() string

String interface.

func (*EvalOptions) This

This set the obj as ThisObj.

type EventHandler added in v0.118.0

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

EventHandler binds one protocol event type to its callback. Construct it with On.

func On added in v0.118.0

func On[E proto.Event](callback func(*E, proto.TargetSessionID) bool) EventHandler

On handles events of type E. Return true to stop the EachEvent wait, or false to continue. The session ID identifies the page that emitted a browser event. Events are shallow copies; treat their referenced data as read-only.

type ExpectElementError

type ExpectElementError struct {
	*proto.RuntimeRemoteObject
}

ExpectElementError error.

func (*ExpectElementError) Error

func (e *ExpectElementError) Error() string

func (*ExpectElementError) Is

func (e *ExpectElementError) Is(err error) bool

Is interface.

type ExpectElementsError

type ExpectElementsError struct {
	*proto.RuntimeRemoteObject
}

ExpectElementsError error.

func (*ExpectElementsError) Error

func (e *ExpectElementsError) Error() string

func (*ExpectElementsError) Is

func (e *ExpectElementsError) Is(err error) bool

Is interface.

type Hijack

type Hijack struct {
	Request  *HijackRequest
	Response *HijackResponse
	OnError  func(error)

	// Skip to next handler
	Skip bool

	// CustomState is used to store things for this context
	CustomState any
	// contains filtered or unexported fields
}

Hijack context.

func (*Hijack) ContinueRequest

func (h *Hijack) ContinueRequest(cq *proto.FetchContinueRequest)

ContinueRequest without hijacking. The RequestID will be set by the router, you don't have to set it.

func (*Hijack) LoadResponse

func (h *Hijack) LoadResponse(client *http.Client, loadBody bool) error

LoadResponse will send request to the real destination and load the response as default response to override.

func (*Hijack) MustLoadResponse

func (h *Hijack) MustLoadResponse()

MustLoadResponse is similar to Hijack.LoadResponse.

type HijackRequest

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

HijackRequest context.

func (*HijackRequest) Body

func (ctx *HijackRequest) Body() string

Body returns the captured or SetBody replacement bytes as a Go string, which preserves binary data. Bytes omitted by the browser, such as unavailable file contents, cannot be recovered.

func (*HijackRequest) Header

func (ctx *HijackRequest) Header(key string) string

Header via a key.

func (*HijackRequest) Headers

func (ctx *HijackRequest) Headers() proto.NetworkHeaders

Headers returns a snapshot of the outgoing request headers. Use Req().Header to modify them.

func (*HijackRequest) IsNavigation

func (ctx *HijackRequest) IsNavigation() bool

IsNavigation determines whether the request is a navigation request.

func (*HijackRequest) JSONBody

func (ctx *HijackRequest) JSONBody() jsonvalue.Value

JSONBody of the request.

func (*HijackRequest) Method

func (ctx *HijackRequest) Method() string

Method of the request.

func (*HijackRequest) Req

func (ctx *HijackRequest) Req() *http.Request

Req returns the underlying http.Request instance that will be used to send the request.

func (*HijackRequest) SetBody

func (ctx *HijackRequest) SetBody(obj any) *HijackRequest

SetBody replaces the body and its replay function and content length. Byte slices and strings are used directly as data; other values are JSON encoded.

func (*HijackRequest) SetContext

func (ctx *HijackRequest) SetContext(c context.Context) *HijackRequest

SetContext of the underlying http.Request instance.

func (*HijackRequest) Type

Type of the resource.

func (*HijackRequest) URL

func (ctx *HijackRequest) URL() *url.URL

URL of the request.

type HijackResponse

type HijackResponse struct {
	RawResponse *http.Response
	// contains filtered or unexported fields
}

HijackResponse context.

func (*HijackResponse) AddHeader

func (ctx *HijackResponse) AddHeader(pairs ...string) *HijackResponse

AddHeader appends key-value pairs to the end of the response headers. Duplicate keys will be preserved.

func (*HijackResponse) Body

func (ctx *HijackResponse) Body() string

Body of the payload.

func (*HijackResponse) Fail

Fail request.

func (*HijackResponse) Headers

func (ctx *HijackResponse) Headers() http.Header

Headers returns the clone of response headers. Use SetHeader to replace values or AddHeader to retain repeated values.

func (*HijackResponse) Payload

func (ctx *HijackResponse) Payload() *proto.FetchFulfillRequest

Payload to respond the request from the browser.

func (*HijackResponse) SetBody

func (ctx *HijackResponse) SetBody(obj any) *HijackResponse

SetBody of the payload, if obj is []byte or string, raw body will be used, else it will be encoded as json.

func (*HijackResponse) SetHeader

func (ctx *HijackResponse) SetHeader(pairs ...string) *HijackResponse

SetHeader replaces all values for each case-insensitive header name.

type HijackRouter

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

HijackRouter context.

func (*HijackRouter) Add

func (r *HijackRouter) Add(pattern string, resourceType proto.NetworkResourceType, handler func(*Hijack)) error

Add a hijack handler using FetchRequestPattern.URLPattern glob syntax. '?' matches exactly one character, as documented by CDP. Chrome versions that also pause a zero-character match have that request continued without handling. Failed updates leave the router's previous handlers and filters intact.

func (*HijackRouter) MustAdd

func (r *HijackRouter) MustAdd(pattern string, handler func(*Hijack)) *HijackRouter

MustAdd is similar to HijackRouter.Add.

func (*HijackRouter) MustRemove

func (r *HijackRouter) MustRemove(pattern string) *HijackRouter

MustRemove is similar to HijackRouter.Remove.

func (*HijackRouter) MustStop

func (r *HijackRouter) MustStop()

MustStop is similar to HijackRouter.Stop.

func (*HijackRouter) Remove

func (r *HijackRouter) Remove(pattern string) error

Remove handler via the pattern.

func (*HijackRouter) Run

func (r *HijackRouter) Run() error

Run waits until Stop, cancellation, or a connection error, then releases Fetch. Setup, event-wait, and cleanup errors are returned. Handler errors use OnError.

func (*HijackRouter) Stop

func (r *HijackRouter) Stop() error

Stop the router.

type InvisibleShapeError

type InvisibleShapeError struct {
	*Element
}

InvisibleShapeError error.

func (*InvisibleShapeError) Error

func (e *InvisibleShapeError) Error() string

Error ...

func (*InvisibleShapeError) Is

func (e *InvisibleShapeError) Is(err error) bool

Is interface.

func (*InvisibleShapeError) Unwrap

func (e *InvisibleShapeError) Unwrap() error

Unwrap ...

type JSONSerializationError added in v0.120.0

type JSONSerializationError struct {
	Message string
}

JSONSerializationError describes a result that could not be serialized under the Page.EvalJSON contract.

func (*JSONSerializationError) Error added in v0.120.0

func (e *JSONSerializationError) Error() string

type KeyAction

type KeyAction struct {
	Type KeyActionType
	Key  input.Key
}

KeyAction to perform.

type KeyActionType

type KeyActionType int

KeyActionType enum.

const (
	KeyActionPress KeyActionType = iota
	KeyActionRelease
	KeyActionTypeKey
)

KeyActionTypes.

type KeyActions

type KeyActions struct {
	Actions []KeyAction
	// contains filtered or unexported fields
}

KeyActions to simulate.

func (*KeyActions) Do

func (ka *KeyActions) Do() (err error)

Do the actions.

func (*KeyActions) MustDo

func (ka *KeyActions) MustDo()

MustDo is similar to KeyActions.Do.

func (*KeyActions) Press

func (ka *KeyActions) Press(keys ...input.Key) *KeyActions

Press keys schedules their release at the end of actions. If an action fails, Do also attempts to release keys introduced by this sequence within five seconds.

func (*KeyActions) Release

func (ka *KeyActions) Release(keys ...input.Key) *KeyActions

Release keys.

func (*KeyActions) Type

func (ka *KeyActions) Type(keys ...input.Key) *KeyActions

Type will release the key immediately after the pressing.

type Keyboard

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

Keyboard represents the keyboard on a page, it's always related the main frame.

func (*Keyboard) MustType

func (k *Keyboard) MustType(key ...input.Key) *Keyboard

MustType is similar to Keyboard.Type.

func (*Keyboard) Press

func (k *Keyboard) Press(key input.Key) error

Press the key down. To input characters that are not on the keyboard, such as Chinese or Japanese, you should use method like Page.InsertText.

func (*Keyboard) Release

func (k *Keyboard) Release(key input.Key) error

Release the key.

func (*Keyboard) Type

func (k *Keyboard) Type(keys ...input.Key) (err error)

Type releases the key after the press.

type Message

type Message struct {
	SessionID proto.TargetSessionID
	Method    string
	// contains filtered or unexported fields
}

Message represents a cdp.Event. Do not copy it after first use.

func (*Message) Load

func (msg *Message) Load[E proto.Event](out *E) bool

Load decodes a matching event into out. E is the concrete protocol event type. Subscribers loading the same type share a cached decode and receive a shallow copy. Treat referenced data, such as slices and nested pointers, as read-only.

type Mouse

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

Mouse represents the mouse on a page, it's always related the main frame.

func (*Mouse) Click

func (m *Mouse) Click(button proto.InputMouseButton, clickCount int) error

Click the button. It's the combination of Mouse.Down and Mouse.Up.

func (*Mouse) Down

func (m *Mouse) Down(button proto.InputMouseButton, clickCount int) error

Down holds the button down.

func (*Mouse) MoveAlong

func (m *Mouse) MoveAlong(guide func() (proto.Point, bool)) error

MoveAlong the guide function. Every time the guide function is called it should return the next mouse position, return true to stop. Read the source code of Mouse.MoveLinear as an example to use this method.

func (*Mouse) MoveLinear

func (m *Mouse) MoveLinear(to proto.Point, steps int) error

MoveLinear to the absolute position with the given steps. Such as move from (0,0) to (6,6) with 3 steps, the mouse will first move to (2,2) then (4,4) then (6,6).

func (*Mouse) MoveTo

func (m *Mouse) MoveTo(p proto.Point) error

MoveTo the absolute position.

func (*Mouse) MustClick

func (m *Mouse) MustClick(button proto.InputMouseButton) *Mouse

MustClick is similar to Mouse.Click.

func (*Mouse) MustDown

func (m *Mouse) MustDown(button proto.InputMouseButton) *Mouse

MustDown is similar to Mouse.Down.

func (*Mouse) MustMoveTo

func (m *Mouse) MustMoveTo(x, y float64) *Mouse

MustMoveTo is similar to [Mouse.Move].

func (*Mouse) MustScroll

func (m *Mouse) MustScroll(x, y float64) *Mouse

MustScroll is similar to Mouse.Scroll.

func (*Mouse) MustUp

func (m *Mouse) MustUp(button proto.InputMouseButton) *Mouse

MustUp is similar to Mouse.Up.

func (*Mouse) Position

func (m *Mouse) Position() proto.Point

Position of current cursor.

func (*Mouse) Scroll

func (m *Mouse) Scroll(offsetX, offsetY float64, steps int) error

Scroll the relative offset with specified steps.

func (*Mouse) Up

func (m *Mouse) Up(button proto.InputMouseButton, clickCount int) error

Up releases the button.

type NavigationError struct {
	Reason string
}

NavigationError error.

func (e *NavigationError) Error() string
func (e *NavigationError) Is(err error) bool

Is interface.

type NoPointerEventsError

type NoPointerEventsError struct {
	*Element
}

NoPointerEventsError error.

func (*NoPointerEventsError) Error

func (e *NoPointerEventsError) Error() string

Error ...

func (*NoPointerEventsError) Is

func (e *NoPointerEventsError) Is(err error) bool

Is interface.

func (*NoPointerEventsError) Unwrap

func (e *NoPointerEventsError) Unwrap() error

Unwrap ...

type NoShadowRootError

type NoShadowRootError struct {
	*Element
}

NoShadowRootError error.

func (*NoShadowRootError) Error

func (e *NoShadowRootError) Error() string

Error ...

func (*NoShadowRootError) Is

func (e *NoShadowRootError) Is(err error) bool

Is interface.

type NotInteractableError

type NotInteractableError struct{}

NotInteractableError error. Check the doc of Element.Interactable for details.

func (*NotInteractableError) Error

func (e *NotInteractableError) Error() string

type ObjectNotFoundError

type ObjectNotFoundError struct {
	*proto.RuntimeRemoteObject
}

ObjectNotFoundError error.

func (*ObjectNotFoundError) Error

func (e *ObjectNotFoundError) Error() string

func (*ObjectNotFoundError) Is

func (e *ObjectNotFoundError) Is(err error) bool

Is interface.

type Page

type Page struct {
	// TargetID is a unique ID for a remote page.
	// It's usually used in events sent from the browser to tell which page an event belongs to.
	TargetID proto.TargetTargetID

	// FrameID is a unique ID for a browsing context.
	// Usually, different FrameID means different javascript execution context.
	// Frames in one renderer share a TargetID; frames in another renderer have
	// their own target and session.
	FrameID proto.PageFrameID

	// SessionID is a unique ID for a page attachment to a controller.
	// It's usually used in transport layer to tell which page to send the control signal.
	// A page can attached to multiple controllers, the browser uses it distinguish controllers.
	SessionID proto.TargetSessionID

	// devices
	Mouse    *Mouse
	Keyboard *Keyboard
	Touch    *Touch
	// contains filtered or unexported fields
}

Page represents the webpage. We try to hold as less states as possible. When a page is closed by Rod or not all the ongoing operations an events on it will abort.

Example (Pool)

We can use rod.PagePool to concurrently control and reuse pages.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"sync"
	"time"

	"github.com/rah-0/rod"
)

func main() {
	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_, _ = fmt.Fprint(w, `<!doctype html><title>Pooled page</title>`)
	}))
	defer server.Close()

	ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
	defer cancel()
	browser := rod.New().Context(ctx).NoDefaultDevice().MustConnect()
	defer browser.MustClose()

	// We create a pool that will hold at most 3 pages which means the max concurrency is 3
	pool := rod.NewPagePool(3)

	// Create a page if needed
	create := func() *rod.Page {
		// We use MustIncognito to isolate pages with each other
		return browser.MustIncognito().MustPage()
	}

	yourJob := func() {
		page := pool.MustGet(create)

		// Put the instance back to the pool after we're done,
		// so the instance can be reused by other goroutines.
		defer pool.Put(page)

		page.MustNavigate(server.URL).MustWaitLoad()
		fmt.Println(page.MustInfo().Title)
	}

	// Run jobs concurrently. Explicit Done preserves cleanup if a Must helper panics.
	wg := sync.WaitGroup{}
	for range "...." {
		wg.Add(1)
		go func() {
			defer wg.Done()
			yourJob()
		}()
	}
	wg.Wait()

	// cleanup pool
	pool.Cleanup(func(p *rod.Page) { p.MustClose() })

}
Output:
Pooled page
Pooled page
Pooled page
Pooled page

func (*Page) Activate

func (p *Page) Activate() (*Page, error)

Activate (focuses) the page.

func (*Page) AddScriptTag

func (p *Page) AddScriptTag(url, content string) error

AddScriptTag to page. If url is empty, content will be used.

func (*Page) AddStyleTag

func (p *Page) AddStyleTag(url, content string) error

AddStyleTag to page. If url is empty, content will be used.

func (*Page) Browser

func (p *Page) Browser() *Browser

Browser of the page.

func (*Page) Call

func (p *Page) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error)

Call implements the proto.Client.

func (*Page) CancelTimeout

func (p *Page) CancelTimeout() *Page

CancelTimeout cancels the current timeout context and returns a clone with the parent context.

func (*Page) CaptureDOMSnapshot

func (p *Page) CaptureDOMSnapshot() (domSnapshot *proto.DOMSnapshotCaptureSnapshotResult, err error)

CaptureDOMSnapshot Returns a document snapshot, including the full DOM tree of the root node (including iframes, template contents, and imported documents) in a flattened array, as well as layout and white-listed computed style information for the nodes. Shadow DOM in the returned DOM tree is flattened. `Documents` The nodes in the DOM tree. The DOMNode at index 0 corresponds to the root document. `Strings` Shared string table that all string properties refer to with indexes. Normally use `Strings` is enough.

func (*Page) Close

func (p *Page) Close() error

Close tries to close page, running its beforeunload hooks, if has any.

func (*Page) Context

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

Context returns a view using ctx for chained operations, including input. Views share their target session, caches, and physical input state. Session termination still ends requests and events even when ctx remains live.

func (*Page) Cookies

func (p *Page) Cookies(urls []string) ([]*proto.NetworkCookie, error)

Cookies returns the page cookies. By default it will return the cookies for current page. The urls is the list of URLs for which applicable cookies will be fetched.

func (*Page) DisableDomain

func (p *Page) DisableDomain(method proto.Request) (func() error, error)

DisableDomain temporarily disables a domain and returns an idempotent function that restores its previous configuration, including after caller cancellation.

func (*Page) EachEvent

func (p *Page) EachEvent(handlers ...EventHandler) func() error

EachEvent subscribes to typed handlers for this page. Returning true from a handler stops the wait. For example, dismiss dialogs until the page is closed:

go page.EachEvent(rod.On(func(e *proto.PageJavascriptDialogOpening, _ proto.TargetSessionID) bool {
    _ = proto.PageHandleJavaScriptDialog{Accept: false}.Call(page)
    return false
}))()

func (*Page) Element

func (p *Page) Element(selector string) (*Element, error)

Element retries until an element in the page that matches the CSS selector, then returns the matched element.

func (*Page) ElementByJS

func (p *Page) ElementByJS(opts *EvalOptions) (*Element, error)

ElementByJS returns the element from the return value of the js function. If sleeper is nil, no retry will be performed. By default, it will retry until the js function doesn't return null. To customize the retry logic, check the examples of Page.Sleeper.

func (*Page) ElementFromNode

func (p *Page) ElementFromNode(node *proto.DOMNode) (*Element, error)

ElementFromNode creates an Element from the node, proto.DOMNodeID or proto.DOMBackendNodeID must be specified.

func (*Page) ElementFromObject

func (p *Page) ElementFromObject(obj *proto.RuntimeRemoteObject) (*Element, error)

ElementFromObject creates an Element from the remote object id.

func (*Page) ElementFromPoint

func (p *Page) ElementFromPoint(x, y int) (*Element, error)

ElementFromPoint creates an Element from the absolute point on the page. The point should include the window scroll offset.

func (*Page) ElementR

func (p *Page) ElementR(selector, jsRegex string) (*Element, error)

ElementR retries until an element in the page that matches the css selector and it's text matches the jsRegex, then returns the matched element.

func (*Page) ElementX

func (p *Page) ElementX(xPath string) (*Element, error)

ElementX retries until an element in the page that matches one of the XPath selectors, then returns the matched element.

func (*Page) Elements

func (p *Page) Elements(selector string) (Elements, error)

Elements returns all elements that match the css selector.

func (*Page) ElementsByJS

func (p *Page) ElementsByJS(opts *EvalOptions) (elements Elements, err error)

ElementsByJS returns the elements from the return value of the js.

func (*Page) ElementsX

func (p *Page) ElementsX(xpath string) (Elements, error)

ElementsX returns all elements that match the XPath selector.

func (*Page) Emulate

func (p *Page) Emulate(device devices.Device) error

Emulate the device, such as iPhone9. If device is devices.Clear, it will clear the override.

func (*Page) EnableDomain

func (p *Page) EnableDomain(method proto.Request) (func() error, error)

EnableDomain shares enablement until its idempotent restore function is called. Setup and bounded restoration errors are returned to the caller.

func (*Page) Eval

func (p *Page) Eval(js string, args ...any) (*proto.RuntimeRemoteObject, error)

Eval is a shortcut for Page.Evaluate with AwaitPromise, ByValue set to true.

func (*Page) EvalJSON added in v0.120.0

func (p *Page) EvalJSON(destination any, js string, args ...any) error

EvalJSON evaluates a trusted JavaScript function, awaits its result, and decodes it into destination using encoding/json. It uses the same function, argument, context, and navigation retry conventions as Page.Eval.

A nil destination discards the awaited result without serializing it. Any other destination must be a non-nil pointer, validated before JavaScript runs.

Serialization uses JSON.stringify with a replacer that rejects undefined, functions, symbols, bigints, and non-finite numbers, including visited nested values. Cycles and throwing serialization hooks also fail. Normal toJSON behavior applies; symbol-keyed and non-enumerable properties are not visited. Project Map, Set, Error, and DOM values into ordinary JSON data as needed.

Errors distinguish destination validation, evaluation, serialization, and decoding. Wrapped evaluation and encoding/json errors preserve their causes. As with Eval, navigation retries do not guarantee exactly-once side effects.

func (*Page) EvalOnNewDocument

func (p *Page) EvalOnNewDocument(js string) (remove func() error, err error)

EvalOnNewDocument Evaluates given script in every frame upon creation (before loading frame's scripts).

func (*Page) Evaluate

func (p *Page) Evaluate(opts *EvalOptions) (res *proto.RuntimeRemoteObject, err error)

Evaluate js on the page.

func (*Page) Event

func (p *Page) Event() <-chan *Message

Event of the page.

func (*Page) Expose

func (p *Page) Expose(name string, fn func(jsonvalue.Value) (any, error)) (stop func() error, err error)

Expose fn to the page's window object with the name. The exposure survives reloads. Go errors and results that cannot be JSON-encoded reject the JavaScript promise with an error message. Replies are delivered in the frame that called the function. Call the idempotent stop function to remove the binding and reload script. Cleanup has its own bounded context. A Go callback already running is not interrupted.

func (*Page) ExposeHelpers

func (p *Page) ExposeHelpers(list ...*js.Function)

ExposeHelpers helper functions to page's js context so that we can use the Devtools' console to debug them.

func (*Page) GetContext

func (p *Page) GetContext() context.Context

GetContext of current instance.

func (*Page) GetNavigationHistory

func (p *Page) GetNavigationHistory() (*proto.PageGetNavigationHistoryResult, error)

GetNavigationHistory get navigation history.

func (*Page) GetResource

func (p *Page) GetResource(url string) ([]byte, error)

GetResource content by the url. Such as image, css, html, etc. Use the proto.PageGetResourceTree to list all the resources.

func (*Page) GetSessionID

func (p *Page) GetSessionID() proto.TargetSessionID

GetSessionID interface.

func (*Page) GetWindow

func (p *Page) GetWindow() (*proto.BrowserBounds, error)

GetWindow position and size info.

func (*Page) HTML

func (p *Page) HTML() (string, error)

HTML of the page.

func (*Page) HandleDialog

func (p *Page) HandleDialog() (
	wait func() (*proto.PageJavascriptDialogOpening, error),
	handle func(*proto.PageHandleJavaScriptDialog) error,
)

HandleDialog accepts or dismisses next JavaScript initiated dialog (alert, confirm, prompt, or onbeforeunload). Because modal dialog will block js, usually you have to trigger the dialog in another goroutine. For example:

wait, handle := page.MustHandleDialog()
go page.MustElement("button").MustClick()
wait()
handle(true, "")

func (*Page) HandleFileDialog

func (p *Page) HandleFileDialog() (func([]string) error, error)

HandleFileDialog returns a function that waits for the next file chooser and sets its files. Completion or cancellation restores the previous interception setting, including when the returned function is never called.

func (*Page) Has

func (p *Page) Has(selector string) (bool, *Element, error)

Has an element that matches the css selector.

func (*Page) HasR

func (p *Page) HasR(selector, jsRegex string) (bool, *Element, error)

HasR an element that matches the css selector and its display text matches the jsRegex.

func (*Page) HasX

func (p *Page) HasX(selector string) (bool, *Element, error)

HasX an element that matches the XPath selector.

func (*Page) HijackRequests

func (p *Page) HijackRequests() *HijackRouter

HijackRequests creates a new router instance for requests hijacking. When use Fetch domain outside the router should be stopped. Enabling hijacking disables page caching, but such as 304 Not Modified will still work as expected. The entire process of hijacking one request:

browser --req-> rod ---> server ---> rod --res-> browser

The --req-> and --res-> are the parts that can be modified.

func (*Page) Info

func (p *Page) Info() (*proto.TargetTargetInfo, error)

Info of the page, such as the URL or title of the page.

func (*Page) InsertText

func (p *Page) InsertText(text string) error

InsertText is like pasting text into the page.

func (*Page) IsIframe

func (p *Page) IsIframe() bool

IsIframe tells if it's iframe.

func (*Page) KeyActions

func (p *Page) KeyActions() *KeyActions

KeyActions simulates the type actions on a physical keyboard. Useful when input shortcuts like ctrl+enter .

func (*Page) LoadState

func (p *Page) LoadState(method proto.Request) (has bool)

LoadState into the method.

func (*Page) MustActivate

func (p *Page) MustActivate() *Page

MustActivate is similar to Page.Activate.

func (*Page) MustAddScriptTag

func (p *Page) MustAddScriptTag(url string) *Page

MustAddScriptTag is similar to Page.AddScriptTag.

func (*Page) MustAddStyleTag

func (p *Page) MustAddStyleTag(url string) *Page

MustAddStyleTag is similar to Page.AddStyleTag.

func (*Page) MustCaptureDOMSnapshot

func (p *Page) MustCaptureDOMSnapshot() (domSnapshot *proto.DOMSnapshotCaptureSnapshotResult)

MustCaptureDOMSnapshot is similar to Page.CaptureDOMSnapshot.

func (*Page) MustClose

func (p *Page) MustClose()

MustClose is similar to Page.Close.

func (*Page) MustCookies

func (p *Page) MustCookies(urls ...string) []*proto.NetworkCookie

MustCookies is similar to Page.Cookies.

func (*Page) MustElement

func (p *Page) MustElement(selector string) *Element

MustElement is similar to Page.Element.

func (*Page) MustElementByJS

func (p *Page) MustElementByJS(js string, params ...any) *Element

MustElementByJS is similar to Page.ElementByJS.

func (*Page) MustElementFromNode

func (p *Page) MustElementFromNode(node *proto.DOMNode) *Element

MustElementFromNode is similar to Page.ElementFromNode.

func (*Page) MustElementFromPoint

func (p *Page) MustElementFromPoint(left, top int) *Element

MustElementFromPoint is similar to Page.ElementFromPoint.

func (*Page) MustElementR

func (p *Page) MustElementR(selector, jsRegex string) *Element

MustElementR is similar to Page.ElementR.

func (*Page) MustElementX

func (p *Page) MustElementX(xPath string) *Element

MustElementX is similar to Page.ElementX.

func (*Page) MustElements

func (p *Page) MustElements(selector string) Elements

MustElements is similar to Page.Elements.

func (*Page) MustElementsByJS

func (p *Page) MustElementsByJS(js string, params ...any) Elements

MustElementsByJS is similar to Page.ElementsByJS.

func (*Page) MustElementsX

func (p *Page) MustElementsX(xpath string) Elements

MustElementsX is similar to Page.ElementsX.

func (*Page) MustEmulate

func (p *Page) MustEmulate(device devices.Device) *Page

MustEmulate is similar to Page.Emulate.

func (*Page) MustEval

func (p *Page) MustEval(js string, params ...any) jsonvalue.Value

MustEval is similar to Page.Eval.

func (*Page) MustEvalOnNewDocument

func (p *Page) MustEvalOnNewDocument(js string)

MustEvalOnNewDocument is similar to Page.EvalOnNewDocument.

func (*Page) MustEvaluate

func (p *Page) MustEvaluate(opts *EvalOptions) *proto.RuntimeRemoteObject

MustEvaluate is similar to Page.Evaluate.

func (*Page) MustExpose

func (p *Page) MustExpose(name string, fn func(jsonvalue.Value) (any, error)) (stop func())

MustExpose is similar to Page.Expose.

func (*Page) MustGetWindow

func (p *Page) MustGetWindow() *proto.BrowserBounds

MustGetWindow is similar to Page.GetWindow.

func (*Page) MustHTML

func (p *Page) MustHTML() string

MustHTML is similar to Page.HTML.

func (*Page) MustHandleDialog

func (p *Page) MustHandleDialog() (wait func() *proto.PageJavascriptDialogOpening, handle func(bool, string))

MustHandleDialog is similar to Page.HandleDialog.

func (*Page) MustHandleFileDialog

func (p *Page) MustHandleFileDialog() func(...string)

MustHandleFileDialog is similar to Page.HandleFileDialog.

func (*Page) MustHas

func (p *Page) MustHas(selector string) bool

MustHas is similar to Page.Has.

func (*Page) MustHasR

func (p *Page) MustHasR(selector, regex string) bool

MustHasR is similar to Page.HasR.

func (*Page) MustHasX

func (p *Page) MustHasX(selector string) bool

MustHasX is similar to Page.HasX.

func (*Page) MustInfo

func (p *Page) MustInfo() *proto.TargetTargetInfo

MustInfo is similar to Page.Info.

func (*Page) MustInsertText

func (p *Page) MustInsertText(text string) *Page

MustInsertText is similar to Page.InsertText.

func (*Page) MustNavigate

func (p *Page) MustNavigate(url string) *Page

MustNavigate is similar to Page.Navigate.

func (*Page) MustNavigateBack

func (p *Page) MustNavigateBack() *Page

MustNavigateBack is similar to Page.NavigateBack.

func (*Page) MustNavigateForward

func (p *Page) MustNavigateForward() *Page

MustNavigateForward is similar to Page.NavigateForward.

func (*Page) MustObjectToJSON

func (p *Page) MustObjectToJSON(obj *proto.RuntimeRemoteObject) jsonvalue.Value

MustObjectToJSON is similar to Page.ObjectToJSON.

func (*Page) MustObjectsToJSON

func (p *Page) MustObjectsToJSON(list []*proto.RuntimeRemoteObject) jsonvalue.Value

MustObjectsToJSON is similar to [Page.ObjectsToJSON].

func (*Page) MustPDF

func (p *Page) MustPDF(toFile ...string) []byte

MustPDF is similar to Page.PDF. If the toFile is "", it Page.will save output to "tmp/pdf" folder, time as the file name.

func (*Page) MustRelease

func (p *Page) MustRelease(obj *proto.RuntimeRemoteObject) *Page

MustRelease is similar to Page.Release.

func (*Page) MustReload

func (p *Page) MustReload() *Page

MustReload is similar to Page.Reload.

func (*Page) MustResetNavigationHistory

func (p *Page) MustResetNavigationHistory() *Page

MustResetNavigationHistory is similar to Page.ResetNavigationHistory.

func (*Page) MustScreenshot

func (p *Page) MustScreenshot(toFile ...string) []byte

MustScreenshot is similar to Page.Screenshot. If the toFile is "", it Page.will save output to "tmp/screenshots" folder, time as the file name.

func (*Page) MustScreenshotFullPage

func (p *Page) MustScreenshotFullPage(toFile ...string) []byte

MustScreenshotFullPage is similar to [Page.ScreenshotFullPage]. If the toFile is "", it Page.will save output to "tmp/screenshots" folder, time as the file name.

func (*Page) MustScrollScreenshot

func (p *Page) MustScrollScreenshot(toFile ...string) []byte

MustScrollScreenshot is similar to Page.ScrollScreenshot. If the toFile is "", it Page.will save output to "tmp/screenshots" folder, time as the file name.

func (*Page) MustSearch

func (p *Page) MustSearch(query string) *Element

MustSearch is similar to Page.Search. It only returns the first element in the search result.

func (*Page) MustSetBlockedURLs

func (p *Page) MustSetBlockedURLs(urls ...string) *Page

MustSetBlockedURLs is similar to Page.SetBlockedURLs.

func (*Page) MustSetCookies

func (p *Page) MustSetCookies(cookies ...*proto.NetworkCookieParam) *Page

MustSetCookies is similar to Page.SetCookies. If the len(cookies) is 0 it will clear all the cookies.

func (*Page) MustSetDocumentContent

func (p *Page) MustSetDocumentContent(html string) *Page

MustSetDocumentContent is similar to Page.SetDocumentContent.

func (*Page) MustSetExtraHeaders

func (p *Page) MustSetExtraHeaders(dict ...string) (cleanup func())

MustSetExtraHeaders is similar to Page.SetExtraHeaders.

func (*Page) MustSetUserAgent

func (p *Page) MustSetUserAgent(req *proto.NetworkSetUserAgentOverride) *Page

MustSetUserAgent is similar to Page.SetUserAgent.

func (*Page) MustSetViewport

func (p *Page) MustSetViewport(width, height int, deviceScaleFactor float64, mobile bool) *Page

MustSetViewport is similar to Page.SetViewport.

func (*Page) MustSetWindow

func (p *Page) MustSetWindow(left, top, width, height int) *Page

MustSetWindow is similar to Page.SetWindow.

func (*Page) MustStopLoading

func (p *Page) MustStopLoading() *Page

MustStopLoading is similar to Page.StopLoading.

func (*Page) MustTriggerFavicon

func (p *Page) MustTriggerFavicon() *Page

MustTriggerFavicon is similar to [PageTriggerFavicon].

func (*Page) MustWait

func (p *Page) MustWait(js string, params ...any) *Page

MustWait is similar to Page.Wait.

func (*Page) MustWaitDOMStable

func (p *Page) MustWaitDOMStable() *Page

MustWaitDOMStable is similar to Page.WaitDOMStable.

func (*Page) MustWaitElementsMoreThan

func (p *Page) MustWaitElementsMoreThan(selector string, num int) *Page

MustWaitElementsMoreThan is similar to Page.WaitElementsMoreThan.

func (*Page) MustWaitIdle

func (p *Page) MustWaitIdle() *Page

MustWaitIdle is similar to Page.WaitIdle.

func (*Page) MustWaitLoad

func (p *Page) MustWaitLoad() *Page

MustWaitLoad is similar to Page.WaitLoad.

func (*Page) MustWaitNavigation

func (p *Page) MustWaitNavigation() func()

MustWaitNavigation is similar to Page.WaitNavigation.

func (*Page) MustWaitOpen

func (p *Page) MustWaitOpen() (wait func() (newPage *Page))

MustWaitOpen is similar to Page.WaitOpen.

func (*Page) MustWaitRequestIdle

func (p *Page) MustWaitRequestIdle(excludes ...string) (wait func())

MustWaitRequestIdle is similar to Page.WaitRequestIdle.

func (*Page) MustWaitStable

func (p *Page) MustWaitStable() *Page

MustWaitStable is similar to Page.WaitStable.

func (*Page) MustWindowFullscreen

func (p *Page) MustWindowFullscreen() *Page

MustWindowFullscreen is similar to [Page.WindowFullscreen].

func (*Page) MustWindowMaximize

func (p *Page) MustWindowMaximize() *Page

MustWindowMaximize is similar to [Page.WindowMaximize].

func (*Page) MustWindowMinimize

func (p *Page) MustWindowMinimize() *Page

MustWindowMinimize is similar to [Page.WindowMinimize].

func (*Page) MustWindowNormal

func (p *Page) MustWindowNormal() *Page

MustWindowNormal is similar to [Page.WindowNormal].

func (*Page) Navigate

func (p *Page) Navigate(url string) error

Navigate to the url. If the url is empty, "about:blank" will be used. It will return immediately after the server responds the http header.

func (*Page) NavigateBack

func (p *Page) NavigateBack() error

NavigateBack history.

func (*Page) NavigateForward

func (p *Page) NavigateForward() error

NavigateForward history.

func (*Page) ObjectToJSON

func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) (jsonvalue.Value, error)

ObjectToJSON by object id.

func (*Page) Overlay

func (p *Page) Overlay(left, top, width, height float64, msg string) (remove func())

Overlay a rectangle on the main frame with specified message.

func (*Page) PDF

func (p *Page) PDF(req *proto.PagePrintToPDF) (*StreamReader, error)

PDF prints page as PDF.

func (*Page) Race

func (p *Page) Race() *RaceContext

Race creates a context to race selectors.

func (*Page) Release

func (p *Page) Release(obj *proto.RuntimeRemoteObject) error

Release the remote object. Usually, you don't need to call it. When a page is closed or reloaded, all remote objects will be released automatically. It's useful if the page never closes or reloads.

func (*Page) Reload

func (p *Page) Reload() error

Reload page.

func (*Page) ResetNavigationHistory

func (p *Page) ResetNavigationHistory() error

ResetNavigationHistory reset history.

func (*Page) Screenshot

func (p *Page) Screenshot(fullPage bool, req *proto.PageCaptureScreenshot) ([]byte, error)

Screenshot captures the screenshot of current page.

func (*Page) ScrollScreenshot

func (p *Page) ScrollScreenshot(opt *ScrollScreenshotOptions) ([]byte, error)

ScrollScreenshot Scroll screenshot does not adjust the size of the viewport, but achieves it by scrolling and capturing screenshots in a loop, and then stitching them together. Note that this method also has a flaw: when there are elements with fixed positioning on the page (usually header navigation components), these elements will appear repeatedly, you can set the FixedTop parameter to optimize it.

Only support png and jpeg format yet, webP is not supported because no suitable processing library was found in golang.

func (*Page) Search

func (p *Page) Search(query string) (*SearchResult, error)

Search for the given query in the DOM tree until the result count is not zero, before that it will keep retrying. The query can be plain text or css selector or xpath. It will search nested iframes and shadow doms too.

func (*Page) SetBlockedURLs

func (p *Page) SetBlockedURLs(urls []string) error

SetBlockedURLs For some requests that do not want to be triggered, such as some dangerous operations, delete, quit logout, etc. Wildcards ('*') are allowed, such as ["*/api/logout/*","delete"]. NOTE: if you set empty pattern "", it will block all requests.

func (*Page) SetCookies

func (p *Page) SetCookies(cookies []*proto.NetworkCookieParam) error

SetCookies is similar to Browser.SetCookies .

func (*Page) SetDocumentContent

func (p *Page) SetDocumentContent(html string) error

SetDocumentContent sets the page document html content.

func (*Page) SetExtraHeaders

func (p *Page) SetExtraHeaders(dict []string) (func() error, error)

SetExtraHeaders sends extra HTTP headers with requests from this page. The returned function releases its Network domain lease and reports cleanup errors.

func (*Page) SetUserAgent

func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) error

SetUserAgent (browser brand, accept-language, etc) of the page. If req is nil, a default user agent will be used, a typical mac chrome.

func (*Page) SetViewport

func (p *Page) SetViewport(params *proto.EmulationSetDeviceMetricsOverride) error

SetViewport overrides the values of device screen dimensions.

func (*Page) SetWindow

func (p *Page) SetWindow(bounds *proto.BrowserBounds) error

SetWindow location and size.

func (*Page) Sleeper

func (p *Page) Sleeper(sleeper func() utils.Sleeper) *Page

Sleeper returns a clone with the specified sleeper for chained sub-operations.

func (*Page) StartDiagnostics added in v0.120.0

func (p *Page) StartDiagnostics(options DiagnosticsOptions) (*PageDiagnostics, error)

StartDiagnostics subscribes before enabling Runtime and Network, and returns only after both enables succeed. Start before navigation to capture initial scripts. Setup errors release subscriptions and acquired domain ownership.

func (*Page) StopLoading

func (p *Page) StopLoading() error

StopLoading forces the page stop navigation and pending resource fetches.

func (*Page) String

func (p *Page) String() string

String interface.

func (*Page) Timeout

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

Timeout returns a clone with the specified total timeout of all chained sub-operations.

func (*Page) TriggerFavicon

func (p *Page) TriggerFavicon() error

TriggerFavicon supports when browser in headless mode to trigger favicon's request. Pay attention to this function only supported when browser in headless mode, if you call it in no-headless mode, it will raise an error with the message "browser is no-headless".

func (*Page) Wait

func (p *Page) Wait(opts *EvalOptions) error

Wait until the js returns true.

func (*Page) WaitDOMStable

func (p *Page) WaitDOMStable(d time.Duration, diff float64) error

WaitDOMStable waits until the change of the DOM tree is less or equal than diff percent for d duration. Be careful, d is not the max wait timeout, it's the least stable time. If you want to set a timeout you can use the Page.Timeout function.

func (*Page) WaitElementsMoreThan

func (p *Page) WaitElementsMoreThan(selector string, num int) error

WaitElementsMoreThan waits until there are more than num elements that match the selector.

func (*Page) WaitEvent

func (p *Page) WaitEvent[E proto.Event](out *E) func() error

WaitEvent loads the next matching event into out. E is a concrete protocol event type.

func (*Page) WaitIdle

func (p *Page) WaitIdle(timeout time.Duration) (err error)

WaitIdle waits until the next window.requestIdleCallback is called.

func (*Page) WaitLoad

func (p *Page) WaitLoad() error

WaitLoad waits for the `window.onload` event, it returns immediately if the event is already fired.

func (*Page) WaitNavigation

func (p *Page) WaitNavigation(name proto.PageLifecycleEventName) func() error

WaitNavigation wait for a page lifecycle event when navigating. Usually you will wait for proto.PageLifecycleEventNameNetworkAlmostIdle.

func (*Page) WaitOpen

func (p *Page) WaitOpen() func() (*Page, error)

WaitOpen waits for the next new page opened by the current one.

func (*Page) WaitRepaint

func (p *Page) WaitRepaint() error

WaitRepaint waits until the next repaint. Doc: https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame

func (*Page) WaitRequestIdle

func (p *Page) WaitRequestIdle(
	d time.Duration,
	includes, excludes []string,
	excludeTypes []proto.NetworkResourceType,
) func() error

WaitRequestIdle returns a wait function that waits until no request for d duration. Be careful, d is not the max wait timeout, it's the least idle time. If you want to set a timeout you can use the Page.Timeout function. Use the includes and excludes regexp list to filter the requests by their url.

func (*Page) WaitStable

func (p *Page) WaitStable(d time.Duration) error

WaitStable waits until the page is stable for d duration.

func (*Page) WithCancel

func (p *Page) WithCancel() (*Page, func())

WithCancel returns a clone with a context cancel function.

func (*Page) WithPanic

func (p *Page) WithPanic(fail func(any)) *Page

WithPanic returns a page clone with the specified panic function. The fail must stop the current goroutine's execution immediately, such as use runtime.Goexit or panic inside it.

type PageCloseCanceledError

type PageCloseCanceledError struct{}

PageCloseCanceledError error.

func (*PageCloseCanceledError) Error

func (e *PageCloseCanceledError) Error() string

type PageDiagnostics added in v0.120.0

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

PageDiagnostics collects events delivered to one page's CDP session, including its same-process frames. It does not attach to workers, popups or cross-process frames. Snapshot and Stop may be called concurrently.

func (*PageDiagnostics) Snapshot added in v0.120.0

func (d *PageDiagnostics) Snapshot() DiagnosticsSnapshot

Snapshot copies all currently processed records. It does not drain the event queue. Console previews are abbreviated payload representations, not full object snapshots or Chrome DevTools formatting; getters are never invoked.

func (*PageDiagnostics) Stop added in v0.120.0

Stop is idempotent. It processes events through a private Runtime binding call in an isolated world, then releases its subscriptions and domain ownership. This protocol boundary does not wait for future timers, promises or requests. Cancellation or target closure returns the retained data and an error matching ErrDiagnosticsIncomplete. Draining and cleanup each have a StopTimeout budget.

type PageError added in v0.120.0

type PageError struct {
	ExceptionID int
	Text        string
	DiagnosticLocation
}

PageError is an unhandled exception that has not subsequently been revoked.

type PageNotFoundError

type PageNotFoundError struct{}

PageNotFoundError error.

func (*PageNotFoundError) Error

func (e *PageNotFoundError) Error() string

type Pages

type Pages []*Page

Pages provides some helpers to deal with page list.

func (Pages) Empty

func (ps Pages) Empty() bool

Empty returns true if the list is empty.

func (Pages) Find

func (ps Pages) Find(selector string) (*Page, error)

Find the page that has the specified element with the css selector.

func (Pages) FindByURL

func (ps Pages) FindByURL(jsRegex string) (*Page, error)

FindByURL returns the page that has the url that matches the jsRegex.

func (Pages) First

func (ps Pages) First() *Page

First returns the first page, if the list is empty returns nil.

func (Pages) Last

func (ps Pages) Last() *Page

Last returns the last page, if the list is empty returns nil.

func (Pages) MustFind

func (ps Pages) MustFind(selector string) *Page

MustFind is similar to [Browser.Find].

func (Pages) MustFindByURL

func (ps Pages) MustFindByURL(regex string) *Page

MustFindByURL is similar to [Page.FindByURL].

type Pool

type Pool[T any] chan *T

Pool is used to thread-safely limit the number of elements at the same time. It's a common practice to use a channel to limit concurrency, it's not special for rod. This helper is more like an example to use Go Channel. Reference: https://golang.org/doc/effective_go#channels

func NewBrowserPool

func NewBrowserPool(limit int) Pool[Browser]

NewBrowserPool instance.

func NewPagePool

func NewPagePool(limit int) Pool[Page]

NewPagePool instance.

func NewPool

func NewPool[T any](limit int) Pool[T]

NewPool instance.

func (Pool[T]) Cleanup

func (p Pool[T]) Cleanup(iteratee func(*T))

Cleanup helper.

func (Pool[T]) Get

func (p Pool[T]) Get(create func() (*T, error)) (elem *T, err error)

Get a elem from the pool, allow error. Use the [Pool[T].Put] to make it reusable later.

func (Pool[T]) MustGet

func (p Pool[T]) MustGet(create func() *T) *T

MustGet an elem from the pool. Use the [Pool[T].Put] to make it reusable later.

func (Pool[T]) Put

func (p Pool[T]) Put(elem *T)

Put an elem back to the pool.

type RaceContext

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

RaceContext stores the branches to race.

func (*RaceContext) Do

func (rc *RaceContext) Do() (*Element, error)

Do the race.

func (*RaceContext) Element

func (rc *RaceContext) Element(selector string) *RaceContext

Element is similar to Page.Element.

func (*RaceContext) ElementByJS

func (rc *RaceContext) ElementByJS(opts *EvalOptions) *RaceContext

ElementByJS is similar to Page.ElementByJS.

func (*RaceContext) ElementFunc

func (rc *RaceContext) ElementFunc(fn func(*Page) (*Element, error)) *RaceContext

ElementFunc takes a custom function to determine race success.

func (*RaceContext) ElementR

func (rc *RaceContext) ElementR(selector, regex string) *RaceContext

ElementR is similar to Page.ElementR.

func (*RaceContext) ElementX

func (rc *RaceContext) ElementX(selector string) *RaceContext

ElementX is similar to Page.ElementX.

func (*RaceContext) Handle

func (rc *RaceContext) Handle(callback func(*Element) error) *RaceContext

Handle adds a callback function to the most recent chained selector. The callback function is run, if the corresponding selector is present first, in the Race condition.

func (*RaceContext) MustDo

func (rc *RaceContext) MustDo() *Element

MustDo is similar to RaceContext.Do.

func (*RaceContext) MustElementByJS

func (rc *RaceContext) MustElementByJS(js string, params []any) *RaceContext

MustElementByJS is similar to RaceContext.ElementByJS.

func (*RaceContext) MustHandle

func (rc *RaceContext) MustHandle(callback func(*Element)) *RaceContext

MustHandle is similar to RaceContext.Handle.

func (*RaceContext) Search

func (rc *RaceContext) Search(query string) *RaceContext

Search is similar to Page.Search.

type ResourceFailure added in v0.120.0

type ResourceFailure struct {
	RequestID     proto.NetworkRequestID
	URL           string
	Type          proto.NetworkResourceType
	Status        int
	ErrorText     string
	BlockedReason proto.NetworkBlockedReason
	Canceled      bool
}

ResourceFailure correlates an HTTP error and any subsequent loading failure. URL can be empty when no request or response was observed for RequestID.

type ScrollScreenshotOptions

type ScrollScreenshotOptions struct {
	// Format (optional) Image compression format (defaults to png).
	Format proto.PageCaptureScreenshotFormat `json:"format,omitempty"`

	// Quality (optional) Compression quality from range [0..100] (jpeg only).
	Quality *int `json:"quality,omitempty"`

	// FixedTop (optional) The number of pixels to skip from the top.
	// It is suitable for optimizing the screenshot effect when there is a fixed
	// positioning element at the top of the page.
	FixedTop float64

	// FixedBottom (optional) The number of pixels to skip from the bottom.
	FixedBottom float64

	// WaitPerScroll until no animation (default is 300ms)
	WaitPerScroll time.Duration
}

ScrollScreenshotOptions is the options for the ScrollScreenshot.

type SearchResult

type SearchResult struct {
	*proto.DOMPerformSearchResult

	// First element in the search result
	First *Element
	// contains filtered or unexported fields
}

SearchResult handler.

func (*SearchResult) All

func (s *SearchResult) All() (Elements, error)

All returns all elements.

func (*SearchResult) Get

func (s *SearchResult) Get(i, l int) (Elements, error)

Get l elements at the index of i from the remote search result.

func (*SearchResult) Release

func (s *SearchResult) Release() error

Release discards the remote search result and restores domain ownership. It is idempotent and uses a bounded context independent of the search context.

type SelectorType

type SelectorType string

SelectorType enum.

const (
	// SelectorTypeRegex type.
	SelectorTypeRegex SelectorType = "regex"
	// SelectorTypeCSSSector type.
	SelectorTypeCSSSector SelectorType = "css-selector"
	// SelectorTypeText type.
	SelectorTypeText SelectorType = "text"
)

type StreamReader

type StreamReader struct {
	// Offset, when non-nil, is advanced by the number of bytes received from CDP.
	Offset *int
	// contains filtered or unexported fields
}

StreamReader for browser data stream.

func NewStreamReader

func NewStreamReader(c proto.Client, h proto.IOStreamHandle) *StreamReader

NewStreamReader instance.

func (*StreamReader) Close

func (sr *StreamReader) Close() error

Close the stream, discard any temporary backing storage.

func (*StreamReader) Read

func (sr *StreamReader) Read(p []byte) (n int, err error)

type Touch

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

Touch presents a touch device, such as a hand with fingers, each finger is a proto.InputTouchPoint. Touch events is stateless, we use the struct here only as a namespace to make the API style unified.

func (*Touch) Cancel

func (t *Touch) Cancel() error

Cancel touch action.

func (*Touch) End

func (t *Touch) End() error

End touch action.

func (*Touch) Move

func (t *Touch) Move(points ...*proto.InputTouchPoint) error

Move touch points. Use the proto.InputTouchPoint.ID (Touch.identifier) to track points. Doc: https://developer.mozilla.org/en-US/docs/Web/API/Touch_events

func (*Touch) MustCancel

func (t *Touch) MustCancel() *Touch

MustCancel is similar to Touch.Cancel.

func (*Touch) MustEnd

func (t *Touch) MustEnd() *Touch

MustEnd is similar to Touch.End.

func (*Touch) MustMove

func (t *Touch) MustMove(points ...*proto.InputTouchPoint) *Touch

MustMove is similar to Touch.Move.

func (*Touch) MustStart

func (t *Touch) MustStart(points ...*proto.InputTouchPoint) *Touch

MustStart is similar to Touch.Start.

func (*Touch) MustTap

func (t *Touch) MustTap(x, y float64) *Touch

MustTap is similar to Touch.Tap.

func (*Touch) Start

func (t *Touch) Start(points ...*proto.InputTouchPoint) error

Start a touch action.

func (*Touch) Tap

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

Tap dispatches a touchstart and touchend event.

type TraceType

type TraceType string

TraceType for logger.

const (
	// TraceTypeWaitRequestsIdle type.
	TraceTypeWaitRequestsIdle TraceType = "wait requests idle"

	// TraceTypeWaitRequests type.
	TraceTypeWaitRequests TraceType = "wait requests"

	// TraceTypeQuery type.
	TraceTypeQuery TraceType = "query"

	// TraceTypeWait type.
	TraceTypeWait TraceType = "wait"

	// TraceTypeInput type.
	TraceTypeInput TraceType = "input"
)

func (TraceType) String

func (t TraceType) String() string

String interface.

type TryError

type TryError struct {
	Value any
	Stack string
}

TryError error.

func (*TryError) Error

func (e *TryError) Error() string

func (*TryError) Is

func (e *TryError) Is(err error) bool

Is interface.

func (*TryError) Unwrap

func (e *TryError) Unwrap() error

Unwrap stdlib interface.

Directories

Path Synopsis
examples
capture command
Run with: go run ./examples/capture [-out DIRECTORY] Capture local page content as PNG and PDF, with desktop and mobile emulation.
Run with: go run ./examples/capture [-out DIRECTORY] Capture local page content as PNG and PDF, with desktop and mobile emulation.
connect-browser command
Run with: go run ./examples/connect-browser
Run with: go run ./examples/connect-browser
download command
Run with: go run ./examples/download Wait for a browser download and validate its saved bytes.
Run with: go run ./examples/download Wait for a browser download and validate its saved bytes.
forms command
Run with: go run ./examples/forms Fill and submit a real multipart form on a local HTTP fixture.
Run with: go run ./examples/forms Fill and submit a real multipart form on a local HTTP fixture.
http-fixture command
Run with: go run ./examples/http-fixture Serve application assets and API responses on a real local HTTP origin.
Run with: go run ./examples/http-fixture Serve application assets and API responses on a real local HTTP origin.
json-evaluation command
Run with: go run ./examples/json-evaluation
Run with: go run ./examples/json-evaluation
launch-managed command
Run with: go run ./examples/launch-managed
Run with: go run ./examples/launch-managed
network command
Run with: go run ./examples/network Configure request headers and cookies before the initial navigation.
Run with: go run ./examples/network Configure request headers and cookies before the initial navigation.
owned-launch command
Run with: go run ./examples/owned-launch
Run with: go run ./examples/owned-launch
page-diagnostics command
Run with: go run ./examples/page-diagnostics
Run with: go run ./examples/page-diagnostics
proxy-auth command
Run with: go run ./examples/proxy-auth Authenticate to a local HTTP proxy and verify that it forwarded the request.
Run with: go run ./examples/proxy-auth Authenticate to a local HTTP proxy and verify that it forwarded the request.
typing command
Run with: go run ./examples/typing
Run with: go run ./examples/typing
fixtures
gen-fonts command
Package main ...
Package main ...
internal
goroutines
Package goroutines captures and filters runtime goroutine stack traces.
Package goroutines captures and filters runtime goroutine stack traces.
observable
Package observable provides Rod's internal ordered event fan-out.
Package observable provides Rod's internal ordered event fan-out.
testutil
Package testutil provides the small set of testing helpers used by Rod.
Package testutil provides the small set of testing helpers used by Rod.
lib
assets
Package assets contains Rod monitor pages and cursor artwork.
Package assets contains Rod monitor pages and cursor artwork.
cdp
Package cdp for application layer communication with browser.
Package cdp for application layer communication with browser.
defaults
Package defaults provides commonly used Rod options.
Package defaults provides commonly used Rod options.
devices
Package devices ...
Package devices ...
devices/generate command
Package main ...
Package main ...
fixture
Package fixture serves browser test pages on a loopback HTTP origin.
Package fixture serves browser test pages on a loopback HTTP origin.
input
Package input ...
Package input ...
js
js/generate command
Package main ...
Package main ...
jsonvalue
Package jsonvalue provides a small, lazy JSON value wrapper.
Package jsonvalue provides a small, lazy JSON value wrapper.
launcher
Package launcher for launching browser utils.
Package launcher for launching browser utils.
launcher/flags
Package flags ...
Package flags ...
launcher/rod-manager command
A server to help launch browser remotely
A server to help launch browser remotely
proto
Package proto is a lib to encode/decode the data of the cdp protocol.
Package proto is a lib to encode/decode the data of the cdp protocol.
proto/generate command
Package main ...
Package main ...
utils
Package utils ...
Package utils ...
utils/rename command
Package main ...
Package main ...
utils/shell command
Package main It helps to launcher a transparent shell under the current shell with some extra environment variables that are required by rod testing.
Package main It helps to launcher a transparent shell under the current shell with some extra environment variables that are required by rod testing.

Jump to

Keyboard shortcuts

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