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 tests/query_test.go.
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)
}
}
Output:
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")
}
}
Output:
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"
"github.com/rah-0/rod/lib/proto"
)
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)
// Answer the proxy's next authentication challenge. Only challenges from this
// proxy receive the credentials.
// We use CLI tool "mitmproxy --proxyauth user:pass" as an example.
go browser.MustHandleAuth(rod.AuthCredentials{
Source: proto.FetchAuthChallengeSourceProxy,
Origin: "http://127.0.0.1:8080",
Username: "user",
Password: "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())
}
Output:
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,
})
}
}
Output:
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
}
Output:
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())
}
Output:
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)
}
}
Output:
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())
}
Output:
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.MustLoad(&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 (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")
}
Output:
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)
}
Output:
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)
}
Output:
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)
}
Output:
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())
}
}
Output:
Example (Search) ¶
Example_search shows how to use Search to get element inside nested iframes or shadow DOMs. It works the same as https://developers.google.com/web/tools/chrome-devtools/dom#search
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) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
switch r.URL.Path {
case "/outer":
_, _ = fmt.Fprint(w, `<iframe src="/inner"></iframe>`)
case "/inner":
_, _ = fmt.Fprint(w, `<div id="host"></div><script>
const shadow = document.querySelector("#host").attachShadow({mode: "open"})
const button = document.createElement("button")
button.id = "activate"
button.textContent = "Activate"
button.onclick = () => { top.document.title = "Activated" }
shadow.append(button)
</script>`)
default:
_, _ = fmt.Fprint(w, `<iframe src="/outer"></iframe>`)
}
}))
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()
// Search crosses both iframe boundaries and finds the shadow DOM button.
page.MustSearch("#activate").MustClick()
page.MustWait(`() => document.title === "Activated"`)
fmt.Println(page.MustInfo().Title)
}
Output: Activated
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 ¶
- Constants
- Variables
- func NotFoundSleeper() utils.Sleeper
- func Try(fn func()) (err error)
- type AuthCredentials
- type Browser
- func (b *Browser) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error)
- func (b *Browser) CancelTimeout() *Browser
- func (b *Browser) Client(c CDPClient) *Browser
- func (b *Browser) Close() error
- func (b *Browser) CloseWithTimeout(timeout time.Duration) error
- func (b *Browser) Connect() error
- func (b *Browser) Context(ctx context.Context) *Browser
- func (b *Browser) ControlURL(url string) *Browser
- func (b *Browser) Decoding(mode proto.Decoding) *Browser
- func (b *Browser) DefaultDevice(d devices.Device) *Browser
- func (b *Browser) DisableDomain(sessionID proto.TargetSessionID, req proto.Request) (func() error, error)
- func (b *Browser) EachEvent(handlers ...EventHandler) func() error
- func (b *Browser) EnableDomain(sessionID proto.TargetSessionID, req proto.Request) (func() error, error)
- func (b *Browser) Event() <-chan *Message
- func (b *Browser) GetContext() context.Context
- func (b *Browser) GetCookies() ([]*proto.NetworkCookie, error)
- func (b *Browser) GetDecoding() proto.Decoding
- func (b *Browser) HandleAuth(credentials AuthCredentials) func() error
- func (b *Browser) HijackRequests() *HijackRouter
- func (b *Browser) IgnoreCertErrors(enable bool) error
- func (b *Browser) Incognito() (*Browser, error)
- func (b *Browser) Launch(l *launcher.Launcher) (err error)
- func (b *Browser) LoadState(sessionID proto.TargetSessionID, method proto.Request) (has bool)
- func (b *Browser) Logger(l utils.Logger) *Browser
- func (b *Browser) Monitor(url string) *Browser
- func (b *Browser) MustClose()
- func (b *Browser) MustConnect() *Browser
- func (b *Browser) MustGetCookies() []*proto.NetworkCookie
- func (b *Browser) MustHandleAuth(credentials AuthCredentials) (wait func())
- func (b *Browser) MustIgnoreCertErrors(enable bool) *Browser
- func (b *Browser) MustIncognito() *Browser
- func (b *Browser) MustPage(url ...string) *Page
- func (b *Browser) MustPageFromTargetID(targetID proto.TargetTargetID) *Page
- func (b *Browser) MustPages() Pages
- func (b *Browser) MustSetCookies(cookies ...*proto.NetworkCookie) *Browser
- func (b *Browser) MustVersion() *proto.BrowserGetVersionResult
- func (b *Browser) MustWaitDownload() func() []byte
- func (b *Browser) NoDefaultDevice() *Browser
- func (b *Browser) Page(opts proto.TargetCreateTarget) (p *Page, err error)
- func (b *Browser) PageFromSession(sessionID proto.TargetSessionID) *Page
- func (b *Browser) PageFromTarget(targetID proto.TargetTargetID) (*Page, error)
- func (b *Browser) Pages() (Pages, error)
- func (b *Browser) RemoveState(key any)
- func (b *Browser) ServeMonitor(host string) string
- func (b *Browser) SetCookies(cookies []*proto.NetworkCookieParam) error
- func (b *Browser) Sleeper(sleeper func() utils.Sleeper) *Browser
- func (b *Browser) SlowMotion(delay time.Duration) *Browser
- func (b *Browser) Timeout(d time.Duration) *Browser
- func (b *Browser) Trace(enable bool) *Browser
- func (b *Browser) Version() (*proto.BrowserGetVersionResult, error)
- func (b *Browser) WaitDownload(dir string) (func() (*proto.BrowserDownloadWillBegin, error), error)
- func (b *Browser) WaitEvent[E proto.Event](out *E) func() error
- func (b *Browser) WithCancel() (*Browser, func())
- func (b *Browser) WithPanic(fail func(any)) *Browser
- type CDPClient
- type ConsoleMessage
- type CoveredError
- type DiagnosticLocation
- type DiagnosticsOptions
- type DiagnosticsSnapshot
- type Drag
- type Element
- func (el *Element) Attribute(name string) (*string, error)
- func (el *Element) BackgroundImage() ([]byte, error)
- func (el *Element) Blur() error
- func (el *Element) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error)
- func (el *Element) CancelTimeout() *Element
- func (el *Element) CanvasToImage(format string, quality float64) ([]byte, error)
- func (el *Element) Click(button proto.InputMouseButton, clickCount int) error
- func (el *Element) ContainsElement(target *Element) (bool, error)
- func (el *Element) Context(ctx context.Context) *Element
- func (el *Element) Describe(depth int, pierce bool) (*proto.DOMNode, error)
- func (el *Element) Disabled() (bool, error)
- func (el *Element) Element(selector string) (*Element, error)
- func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error)
- func (el *Element) ElementR(selector, jsRegex string) (*Element, error)
- func (el *Element) ElementX(xPath string) (*Element, error)
- func (el *Element) Elements(selector string) (Elements, error)
- func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error)
- func (el *Element) ElementsX(xpath string) (Elements, error)
- func (el *Element) Equal(elm *Element) (bool, error)
- func (el *Element) Eval(js string, params ...any) (*proto.RuntimeRemoteObject, error)
- func (el *Element) Evaluate(opts *EvalOptions) (*proto.RuntimeRemoteObject, error)
- func (el *Element) Focus() error
- func (el *Element) Frame() (*Page, error)
- func (el *Element) GetContext() context.Context
- func (el *Element) GetDecoding() proto.Decoding
- func (el *Element) GetSessionID() proto.TargetSessionID
- func (el *Element) GetXPath(optimized bool) (string, error)
- func (el *Element) HTML() (string, error)
- func (el *Element) Has(selector string) (bool, *Element, error)
- func (el *Element) HasR(selector, jsRegex string) (bool, *Element, error)
- func (el *Element) HasX(selector string) (bool, *Element, error)
- func (el *Element) Hover() error
- func (el *Element) Input(text string) error
- func (el *Element) InputColor(color string) error
- func (el *Element) InputTime(t time.Time) error
- func (el *Element) Interactable() (pt *proto.Point, err error)
- func (el *Element) KeyActions() (*KeyActions, error)
- func (el *Element) Matches(selector string) (bool, error)
- func (el *Element) MoveMouseOut() error
- func (el *Element) MustAttribute(name string) *string
- func (el *Element) MustBackgroundImage() []byte
- func (el *Element) MustBlur() *Element
- func (el *Element) MustCanvasToImage() []byte
- func (el *Element) MustClick() *Element
- func (el *Element) MustContainsElement(target *Element) bool
- func (el *Element) MustDescribe() *proto.DOMNode
- func (el *Element) MustDisabled() bool
- func (el *Element) MustDoubleClick() *Element
- func (el *Element) MustElement(selector string) *Element
- func (el *Element) MustElementByJS(js string, params ...any) *Element
- func (el *Element) MustElementR(selector, regex string) *Element
- func (el *Element) MustElementX(xpath string) *Element
- func (el *Element) MustElements(selector string) Elements
- func (el *Element) MustElementsByJS(js string, params ...any) Elements
- func (el *Element) MustElementsX(xpath string) Elements
- func (el *Element) MustEqual(elm *Element) bool
- func (el *Element) MustEval(js string, params ...any) jsonvalue.Value
- func (el *Element) MustFocus() *Element
- func (el *Element) MustFrame() *Page
- func (el *Element) MustGetXPath(optimized bool) string
- func (el *Element) MustHTML() string
- func (el *Element) MustHas(selector string) bool
- func (el *Element) MustHasR(selector, regex string) bool
- func (el *Element) MustHasX(selector string) bool
- func (el *Element) MustHover() *Element
- func (el *Element) MustInput(text string) *Element
- func (el *Element) MustInputColor(color string) *Element
- func (el *Element) MustInputTime(t time.Time) *Element
- func (el *Element) MustInteractable() bool
- func (el *Element) MustKeyActions() *KeyActions
- func (el *Element) MustMatches(selector string) bool
- func (el *Element) MustMoveMouseOut() *Element
- func (el *Element) MustNext() *Element
- func (el *Element) MustParent() *Element
- func (el *Element) MustParents(selector string) Elements
- func (el *Element) MustPrevious() *Element
- func (el *Element) MustProperty(name string) jsonvalue.Value
- func (el *Element) MustRelease()
- func (el *Element) MustRemove()
- func (el *Element) MustResource() []byte
- func (el *Element) MustScreenshot(toFile ...string) []byte
- func (el *Element) MustScrollIntoView() *Element
- func (el *Element) MustSelect(selectors ...string) *Element
- func (el *Element) MustSelectAllText() *Element
- func (el *Element) MustSelectText(regex string) *Element
- func (el *Element) MustSetFiles(paths ...string) *Element
- func (el *Element) MustSetFilesFromMemory(files ...FilePayload) *Element
- func (el *Element) MustShadowRoot() *Element
- func (el *Element) MustShape() *proto.DOMGetContentQuadsResult
- func (el *Element) MustTap() *Element
- func (el *Element) MustText() string
- func (el *Element) MustType(keys ...input.Key) *Element
- func (el *Element) MustVisible() bool
- func (el *Element) MustWait(js string, params ...any) *Element
- func (el *Element) MustWaitEnabled() *Element
- func (el *Element) MustWaitInteractable() *Element
- func (el *Element) MustWaitInvisible() *Element
- func (el *Element) MustWaitLoad() *Element
- func (el *Element) MustWaitStable() *Element
- func (el *Element) MustWaitVisible() *Element
- func (el *Element) MustWaitWritable() *Element
- func (el *Element) Next() (*Element, error)
- func (el *Element) Overlay(msg string) (removeOverlay func())
- func (el *Element) Page() *Page
- func (el *Element) Parent() (*Element, error)
- func (el *Element) Parents(selector string) (Elements, error)
- func (el *Element) Previous() (*Element, error)
- func (el *Element) Property(name string) (jsonvalue.Value, error)
- func (el *Element) Release() error
- func (el *Element) Remove() error
- func (el *Element) Resource() ([]byte, error)
- func (el *Element) Screenshot(format proto.PageCaptureScreenshotFormat, quality int) ([]byte, error)
- func (el *Element) ScrollIntoView() error
- func (el *Element) Select(selectors []string, selected bool, t SelectorType) error
- func (el *Element) SelectAllText() error
- func (el *Element) SelectText(regex string) error
- func (el *Element) SetFiles(paths []string) error
- func (el *Element) SetFilesFromMemory(files []FilePayload) error
- func (el *Element) ShadowRoot() (*Element, error)
- func (el *Element) Shape() (*proto.DOMGetContentQuadsResult, error)
- func (el *Element) Sleeper(sleeper func() utils.Sleeper) *Element
- func (el *Element) String() string
- func (el *Element) Tap() error
- func (el *Element) Text() (string, error)
- func (el *Element) Timeout(d time.Duration) *Element
- func (el *Element) Type(keys ...input.Key) error
- func (el *Element) Visible() (bool, error)
- func (el *Element) Wait(opts *EvalOptions) error
- func (el *Element) WaitEnabled() error
- func (el *Element) WaitInteractable() (pt *proto.Point, err error)
- func (el *Element) WaitInvisible() error
- func (el *Element) WaitLoad() error
- func (el *Element) WaitStable(d time.Duration) error
- func (el *Element) WaitStableRAF() error
- func (el *Element) WaitVisible() error
- func (el *Element) WaitWritable() error
- func (el *Element) WithCancel() (*Element, func())
- func (el *Element) WithPanic(fail func(any)) *Element
- type ElementNotFoundError
- type Elements
- type EvalError
- type EvalOptions
- type EventHandler
- type ExpectElementError
- type ExpectElementsError
- type FilePayload
- type Hijack
- type HijackRequest
- func (ctx *HijackRequest) Body() string
- func (ctx *HijackRequest) Header(key string) string
- func (ctx *HijackRequest) Headers() proto.NetworkHeaders
- func (ctx *HijackRequest) IsNavigation() bool
- func (ctx *HijackRequest) JSONBody() jsonvalue.Value
- func (ctx *HijackRequest) Method() string
- func (ctx *HijackRequest) Req() *http.Request
- func (ctx *HijackRequest) SetBody(obj any) *HijackRequest
- func (ctx *HijackRequest) SetContext(c context.Context) *HijackRequest
- func (ctx *HijackRequest) Type() proto.NetworkResourceType
- func (ctx *HijackRequest) URL() *url.URL
- type HijackResponse
- func (ctx *HijackResponse) AddHeader(pairs ...string) *HijackResponse
- func (ctx *HijackResponse) Body() string
- func (ctx *HijackResponse) Fail(reason proto.NetworkErrorReason) *HijackResponse
- func (ctx *HijackResponse) Headers() http.Header
- func (ctx *HijackResponse) Payload() *proto.FetchFulfillRequest
- func (ctx *HijackResponse) SetBody(obj any) *HijackResponse
- func (ctx *HijackResponse) SetHeader(pairs ...string) *HijackResponse
- type HijackRouter
- func (r *HijackRouter) Add(pattern string, resourceType proto.NetworkResourceType, handler func(*Hijack)) error
- func (r *HijackRouter) ContinueUnparsableURLs(enabled bool) *HijackRouter
- func (r *HijackRouter) MustAdd(pattern string, handler func(*Hijack)) *HijackRouter
- func (r *HijackRouter) MustRemove(pattern string) *HijackRouter
- func (r *HijackRouter) MustStop()
- func (r *HijackRouter) OnError(fn func(error)) *HijackRouter
- func (r *HijackRouter) Remove(pattern string) error
- func (r *HijackRouter) Run() error
- func (r *HijackRouter) Stop() error
- type InvisibleShapeError
- type JSONSerializationError
- type KeyAction
- type KeyActionType
- type KeyActions
- type Keyboard
- type Message
- type Mouse
- func (m *Mouse) Click(button proto.InputMouseButton, clickCount int) error
- func (m *Mouse) Down(button proto.InputMouseButton, clickCount int) error
- func (m *Mouse) MoveAlong(guide func() (proto.Point, bool)) error
- func (m *Mouse) MoveLinear(to proto.Point, steps int) error
- func (m *Mouse) MoveTo(p proto.Point) error
- func (m *Mouse) MustClick(button proto.InputMouseButton) *Mouse
- func (m *Mouse) MustDown(button proto.InputMouseButton) *Mouse
- func (m *Mouse) MustMoveTo(x, y float64) *Mouse
- func (m *Mouse) MustScroll(x, y float64) *Mouse
- func (m *Mouse) MustUp(button proto.InputMouseButton) *Mouse
- func (m *Mouse) Position() proto.Point
- func (m *Mouse) Scroll(offsetX, offsetY float64, steps int) error
- func (m *Mouse) Up(button proto.InputMouseButton, clickCount int) error
- type NavigationError
- type NoPointerEventsError
- type NoShadowRootError
- type NotInteractableError
- type ObjectNotFoundError
- type Page
- func (p *Page) Activate() (*Page, error)
- func (p *Page) AddScriptTag(url, content string) error
- func (p *Page) AddStyleTag(url, content string) error
- func (p *Page) Browser() *Browser
- func (p *Page) Call(ctx context.Context, sessionID, methodName string, params any) (res []byte, err error)
- func (p *Page) CancelTimeout() *Page
- func (p *Page) CaptureDOMSnapshot() (domSnapshot *proto.DOMSnapshotCaptureSnapshotResult, err error)
- func (p *Page) Close() error
- func (p *Page) Context(ctx context.Context) *Page
- func (p *Page) Cookies(urls []string) ([]*proto.NetworkCookie, error)
- func (p *Page) DisableDomain(method proto.Request) (func() error, error)
- func (p *Page) Drag(position proto.Point, data *proto.InputDragData) (*Drag, error)
- func (p *Page) EachEvent(handlers ...EventHandler) func() error
- func (p *Page) Element(selector string) (*Element, error)
- func (p *Page) ElementByJS(opts *EvalOptions) (*Element, error)
- func (p *Page) ElementFromNode(node *proto.DOMNode) (element *Element, err error)
- func (p *Page) ElementFromObject(obj *proto.RuntimeRemoteObject) (*Element, error)
- func (p *Page) ElementFromPoint(x, y int) (*Element, error)
- func (p *Page) ElementR(selector, jsRegex string) (*Element, error)
- func (p *Page) ElementX(xPath string) (*Element, error)
- func (p *Page) Elements(selector string) (Elements, error)
- func (p *Page) ElementsByJS(opts *EvalOptions) (Elements, error)
- func (p *Page) ElementsX(xpath string) (Elements, error)
- func (p *Page) Emulate(device devices.Device) error
- func (p *Page) EnableDomain(method proto.Request) (func() error, error)
- func (p *Page) Eval(js string, args ...any) (*proto.RuntimeRemoteObject, error)
- func (p *Page) EvalJSON(destination any, js string, args ...any) error
- func (p *Page) EvalOnNewDocument(js string) (remove func() error, err error)
- func (p *Page) Evaluate(opts *EvalOptions) (res *proto.RuntimeRemoteObject, err error)
- func (p *Page) Event() <-chan *Message
- func (p *Page) Expose(name string, fn func(jsonvalue.Value) (any, error), onError func(error)) (stop func() error, err error)
- func (p *Page) ExposeHelpers(list ...*js.Function) error
- func (p *Page) GetContext() context.Context
- func (p *Page) GetDecoding() proto.Decoding
- func (p *Page) GetNavigationHistory() (*proto.PageGetNavigationHistoryResult, error)
- func (p *Page) GetResource(url string) ([]byte, error)
- func (p *Page) GetSessionID() proto.TargetSessionID
- func (p *Page) GetWindow() (*proto.BrowserBounds, error)
- func (p *Page) HTML() (_ string, err error)
- func (p *Page) HandleDialog() (wait func() (*proto.PageJavascriptDialogOpening, error), ...)
- func (p *Page) HandleFileDialog() (func([]string) error, error)
- func (p *Page) Has(selector string) (bool, *Element, error)
- func (p *Page) HasR(selector, jsRegex string) (bool, *Element, error)
- func (p *Page) HasX(selector string) (bool, *Element, error)
- func (p *Page) HijackRequests() *HijackRouter
- func (p *Page) Info() (*proto.TargetTargetInfo, error)
- func (p *Page) InsertText(text string) error
- func (p *Page) IsIframe() bool
- func (p *Page) KeyActions() *KeyActions
- func (p *Page) LoadState(method proto.Request) (has bool)
- func (p *Page) MustActivate() *Page
- func (p *Page) MustAddScriptTag(url string) *Page
- func (p *Page) MustAddStyleTag(url string) *Page
- func (p *Page) MustCaptureDOMSnapshot() (domSnapshot *proto.DOMSnapshotCaptureSnapshotResult)
- func (p *Page) MustClose()
- func (p *Page) MustCookies(urls ...string) []*proto.NetworkCookie
- func (p *Page) MustDrag(position proto.Point, data *proto.InputDragData) *Drag
- func (p *Page) MustElement(selector string) *Element
- func (p *Page) MustElementByJS(js string, params ...any) *Element
- func (p *Page) MustElementFromNode(node *proto.DOMNode) *Element
- func (p *Page) MustElementFromPoint(left, top int) *Element
- func (p *Page) MustElementR(selector, jsRegex string) *Element
- func (p *Page) MustElementX(xPath string) *Element
- func (p *Page) MustElements(selector string) Elements
- func (p *Page) MustElementsByJS(js string, params ...any) Elements
- func (p *Page) MustElementsX(xpath string) Elements
- func (p *Page) MustEmulate(device devices.Device) *Page
- func (p *Page) MustEval(js string, params ...any) jsonvalue.Value
- func (p *Page) MustEvalOnNewDocument(js string)
- func (p *Page) MustEvaluate(opts *EvalOptions) *proto.RuntimeRemoteObject
- func (p *Page) MustExpose(name string, fn func(jsonvalue.Value) (any, error), onError func(error)) (stop func())
- func (p *Page) MustExposeHelpers(list ...*js.Function) *Page
- func (p *Page) MustGetWindow() *proto.BrowserBounds
- func (p *Page) MustHTML() string
- func (p *Page) MustHandleDialog() (wait func() *proto.PageJavascriptDialogOpening, handle func(bool, string))
- func (p *Page) MustHandleFileDialog() func(...string)
- func (p *Page) MustHas(selector string) bool
- func (p *Page) MustHasR(selector, regex string) bool
- func (p *Page) MustHasX(selector string) bool
- func (p *Page) MustInfo() *proto.TargetTargetInfo
- func (p *Page) MustInsertText(text string) *Page
- func (p *Page) MustNavigate(url string) *Page
- func (p *Page) MustNavigateBack() *Page
- func (p *Page) MustNavigateForward() *Page
- func (p *Page) MustObjectToJSON(obj *proto.RuntimeRemoteObject) jsonvalue.Value
- func (p *Page) MustObjectsToJSON(list []*proto.RuntimeRemoteObject) jsonvalue.Value
- func (p *Page) MustPDF(toFile ...string) []byte
- func (p *Page) MustRelease(obj *proto.RuntimeRemoteObject) *Page
- func (p *Page) MustReload() *Page
- func (p *Page) MustResetNavigationHistory() *Page
- func (p *Page) MustScreenshot(toFile ...string) []byte
- func (p *Page) MustScreenshotFullPage(toFile ...string) []byte
- func (p *Page) MustScrollScreenshot(toFile ...string) []byte
- func (p *Page) MustSearch(query string) *Element
- func (p *Page) MustSetBlockedURLs(urls ...string) *Page
- func (p *Page) MustSetCookies(cookies ...*proto.NetworkCookieParam) *Page
- func (p *Page) MustSetDocumentContent(html string) *Page
- func (p *Page) MustSetExtraHeaders(dict ...string) (cleanup func())
- func (p *Page) MustSetUserAgent(req *proto.NetworkSetUserAgentOverride) *Page
- func (p *Page) MustSetViewport(width, height int, deviceScaleFactor float64, mobile bool) *Page
- func (p *Page) MustSetWindow(left, top, width, height int) *Page
- func (p *Page) MustStopLoading() *Page
- func (p *Page) MustTriggerFavicon() *Page
- func (p *Page) MustWait(js string, params ...any) *Page
- func (p *Page) MustWaitDOMStable() *Page
- func (p *Page) MustWaitElementsMoreThan(selector string, num int) *Page
- func (p *Page) MustWaitIdle() *Page
- func (p *Page) MustWaitInteractive() *Page
- func (p *Page) MustWaitLoad() *Page
- func (p *Page) MustWaitNavigation() func()
- func (p *Page) MustWaitOpen() (wait func() (newPage *Page))
- func (p *Page) MustWaitRequestIdle(excludes ...string) (wait func())
- func (p *Page) MustWaitStable() *Page
- func (p *Page) MustWindowFullscreen() *Page
- func (p *Page) MustWindowMaximize() *Page
- func (p *Page) MustWindowMinimize() *Page
- func (p *Page) MustWindowNormal() *Page
- func (p *Page) Navigate(url string) error
- func (p *Page) NavigateBack() error
- func (p *Page) NavigateForward() error
- func (p *Page) ObjectToJSON(obj *proto.RuntimeRemoteObject) (jsonvalue.Value, error)
- func (p *Page) Overlay(left, top, width, height float64, msg string) (remove func())
- func (p *Page) PDF(req *proto.PagePrintToPDF) (*StreamReader, error)
- func (p *Page) Race() *RaceContext
- func (p *Page) Release(obj *proto.RuntimeRemoteObject) error
- func (p *Page) Reload() error
- func (p *Page) ResetNavigationHistory() error
- func (p *Page) Screenshot(fullPage bool, req *proto.PageCaptureScreenshot) ([]byte, error)
- func (p *Page) ScrollScreenshot(opt *ScrollScreenshotOptions) ([]byte, error)
- func (p *Page) Search(query string) (*SearchResult, error)
- func (p *Page) SetBlockedURLs(urls []string) error
- func (p *Page) SetCookies(cookies []*proto.NetworkCookieParam) error
- func (p *Page) SetDocumentContent(html string) error
- func (p *Page) SetExtraHeaders(dict []string) (func() error, error)
- func (p *Page) SetUserAgent(req *proto.NetworkSetUserAgentOverride) error
- func (p *Page) SetViewport(params *proto.EmulationSetDeviceMetricsOverride) error
- func (p *Page) SetWindow(bounds *proto.BrowserBounds) error
- func (p *Page) Sleeper(sleeper func() utils.Sleeper) *Page
- func (p *Page) StartDiagnostics(options DiagnosticsOptions) (*PageDiagnostics, error)
- func (p *Page) StopLoading() error
- func (p *Page) String() string
- func (p *Page) Timeout(d time.Duration) *Page
- func (p *Page) TriggerFavicon() error
- func (p *Page) Wait(opts *EvalOptions) error
- func (p *Page) WaitDOMStable(d time.Duration, diff float64) error
- func (p *Page) WaitElementsMoreThan(selector string, num int) error
- func (p *Page) WaitEvent[E proto.Event](out *E) func() error
- func (p *Page) WaitIdle(timeout time.Duration) (err error)
- func (p *Page) WaitInteractive() error
- func (p *Page) WaitLoad() error
- func (p *Page) WaitNavigation(name proto.PageLifecycleEventName) func() error
- func (p *Page) WaitOpen() func() (*Page, error)
- func (p *Page) WaitRepaint() error
- func (p *Page) WaitRequestIdle(d time.Duration, includes, excludes []string, ...) func() error
- func (p *Page) WaitStable(d time.Duration) error
- func (p *Page) WithCancel() (*Page, func())
- func (p *Page) WithPanic(fail func(any)) *Page
- type PageCloseCanceledError
- type PageDiagnostics
- type PageError
- type PageNotFoundError
- type Pages
- type Pool
- type RaceContext
- func (rc *RaceContext) Do() (*Element, error)
- func (rc *RaceContext) Element(selector string) *RaceContext
- func (rc *RaceContext) ElementByJS(opts *EvalOptions) *RaceContext
- func (rc *RaceContext) ElementFunc(fn func(*Page) (*Element, error)) *RaceContext
- func (rc *RaceContext) ElementR(selector, regex string) *RaceContext
- func (rc *RaceContext) ElementX(selector string) *RaceContext
- func (rc *RaceContext) Handle(callback func(*Element) error) *RaceContext
- func (rc *RaceContext) MustDo() *Element
- func (rc *RaceContext) MustElementByJS(js string, params []any) *RaceContext
- func (rc *RaceContext) MustHandle(callback func(*Element)) *RaceContext
- func (rc *RaceContext) Search(query string) *RaceContext
- type ResourceFailure
- type ScrollScreenshotOptions
- type SearchResult
- type SelectorType
- type StreamReader
- type Touch
- func (t *Touch) Cancel() error
- func (t *Touch) End() error
- func (t *Touch) Move(points ...*proto.InputTouchPoint) error
- func (t *Touch) MustCancel() *Touch
- func (t *Touch) MustEnd() *Touch
- func (t *Touch) MustMove(points ...*proto.InputTouchPoint) *Touch
- func (t *Touch) MustStart(points ...*proto.InputTouchPoint) *Touch
- func (t *Touch) MustTap(x, y float64) *Touch
- func (t *Touch) Start(points ...*proto.InputTouchPoint) error
- func (t *Touch) Tap(x, y float64) error
- type TraceType
- type TryError
Examples ¶
- Package (Basic)
- Package (Context_and_EachEvent)
- Package (Context_and_timeout)
- Package (Customize_browser_launch)
- Package (Customize_retry_strategy)
- Package (Direct_cdp)
- Package (Disable_headless_to_debug)
- Package (Download_file)
- Package (Error_handling)
- Package (Eval_reuse_remote_object)
- Package (Handle_events)
- Package (Hijack_requests)
- Package (Log_cdp_traffic)
- Package (Page_pdf)
- Package (Page_screenshot)
- Package (Page_scroll_screenshot)
- Package (Race_selectors)
- Package (Search)
- Package (States)
- Package (Wait_for_animation)
- Package (Wait_for_request)
- Browser (Pool)
- Page (Pool)
Constants ¶
const DefaultMaxResponseBodyBytes int64 = 64 << 20
DefaultMaxResponseBodyBytes is the initial Hijack.MaxResponseBodyBytes. The response body reaches the browser base64 encoded in one CDP message, and Chrome closes the DevTools connection when it receives a message larger than 100 MiB. A 64 MiB body encodes to about 85 MiB. Together with headers within DefaultMaxResponseHeaderBytes, the message stays below Chrome's limit.
const DefaultMaxResponseHeaderBytes int64 = 256 << 10
DefaultMaxResponseHeaderBytes is the initial Hijack.MaxResponseHeaderBytes. Chrome rejects response headers larger than 256 KiB from the network with net::ERR_RESPONSE_HEADERS_TOO_BIG.
Variables ¶
var ( // ErrDragInProgress means a page session already has a drag owned by Rod. ErrDragInProgress = errors.New("a drag is already in progress") // ErrDragEnded means MoveTo or Drop was called after the drag ended. ErrDragEnded = errors.New("drag has ended") // ErrInvalidDrag means the supplied drag data, position, or page is invalid. ErrInvalidDrag = errors.New("invalid drag parameters") )
DefaultLogger for rod.
var DefaultSleeper = func() utils.Sleeper { return utils.BackoffSleeper(10*time.Millisecond, time.Second, nil) }
DefaultSleeper creates a retry sleeper with a 10 ms seed and exponential backoff:
A(0) = 10ms, A(n) = min(A(n-1) * random[1.9, 2.1), 1s)
The first sleep is approximately 19–21 ms. Increasing the interval limits repeated evaluations during longer waits. Use a custom sleeper to choose a different retry cadence.
var ErrAuthCredentials = errors.New("rod: invalid auth credentials")
ErrAuthCredentials means HandleAuth received an invalid challenge source or origin.
var ErrBrowserDisconnected = errors.New("browser connection closed")
ErrBrowserDisconnected means the browser event stream closed before a wait completed.
var ErrCleanupTimeout = errors.New("browser cleanup timeout must be positive")
ErrCleanupTimeout indicates an invalid cleanup time budget.
var ErrDiagnosticsIncomplete = errors.New("rod: incomplete page diagnostics")
ErrDiagnosticsIncomplete means an event could not be decoded or lacked an object that the diagnostics use, or the protocol boundary or cleanup could not finish. The returned snapshot still contains the diagnostics collected so far.
var ErrDiagnosticsOptions = errors.New("rod: invalid diagnostics options")
ErrDiagnosticsOptions means a diagnostics limit is negative.
var ErrDownloadCanceled = errors.New("rod: download canceled")
ErrDownloadCanceled indicates that Chrome canceled the selected download.
var ErrDownloadGUID = errors.New("rod: download GUID is not a single local file name")
ErrDownloadGUID indicates that the browser reported a download GUID that is not a single local file name, so it cannot safely name a file in the download directory.
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.
var ErrExposedFunctionExited = errors.New("rod: exposed function exited without returning")
ErrExposedFunctionExited means an exposed function ended its goroutine with runtime.Goexit, such as through a WithPanic fail function, instead of returning.
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.
var ErrHijackHandlerExited = errors.New("rod: hijack handler exited without returning")
ErrHijackHandlerExited means a hijack handler ended its goroutine with runtime.Goexit, such as through a WithPanic fail function, instead of returning.
var ErrInvalidDataURL = errors.New("invalid data URL")
ErrInvalidDataURL means a value that should be a data URL cannot be decoded, such as a canvas toDataURL result replaced by the page.
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.
var ErrResponseBodyTooLarge = errors.New("rod: hijacked response body exceeds its size limit")
ErrResponseBodyTooLarge means Hijack.LoadResponse stopped reading a body larger than Hijack.MaxResponseBodyBytes.
var ErrResponseHeadersTooLarge = errors.New("rod: hijacked response headers exceed their size limit")
ErrResponseHeadersTooLarge means Hijack.LoadResponse received response headers larger than Hijack.MaxResponseHeaderBytes.
var ErrScrollScreenshotOptions = errors.New("rod: invalid scroll screenshot options")
ErrScrollScreenshotOptions means that ScrollScreenshotOptions are invalid or leave no content to capture between the fixed areas of the viewport.
var ErrScrollScreenshotTooTall = errors.New("rod: page content exceeds the scroll screenshot height limit")
ErrScrollScreenshotTooTall means that the page content is taller than ScrollScreenshotOptions.MaxHeight.
var ErrUnsupportedDomain = errors.New("rod: domain helpers require a domain enable command or Page.setLifecycleEventsEnabled")
ErrUnsupportedDomain means a domain helper received a request other than a domain enable command or Page.setLifecycleEventsEnabled.
Functions ¶
func NotFoundSleeper ¶
NotFoundSleeper returns ErrElementNotFound on the first call.
Types ¶
type AuthCredentials ¶ added in v0.125.0
type AuthCredentials struct {
// Source selects server (HTTP 401) or proxy (HTTP 407) challenges.
Source proto.FetchAuthChallengeSource
// Origin is the challenger's scheme, host, and optional port, such as
// "https://example.com" or "http://proxy.example:3128". For a proxy, use the
// proxy's own origin. The port defaults to 80 for http and 443 for https.
// Use the ASCII (Punycode) form of internationalized host names. It must be
// empty when AnyOrigin is set.
Origin string
// AnyOrigin answers the first challenge from Source whatever its origin.
// When it is false, Origin selects the challenger.
//
// Set it only when the challenger cannot be named in advance, such as a
// proxy that a PAC script selects: the credentials go to whichever
// challenger of Source comes first during the wait. Proxy challenges come
// only from proxies that Chrome sends requests through; Chrome fails a 407
// response from a server that it reaches directly. Server challenges can
// come from any server that the browser loads a resource from, including a
// hostile page's own server, and Basic authentication over http sends the
// credentials unencrypted.
AnyOrigin bool
Username string
Password string
}
AuthCredentials answer HTTP authentication challenges from one challenger.
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()
}
Output:
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 ¶
CancelTimeout cancels the current timeout context and returns a clone with the parent context.
func (*Browser) Close ¶
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
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 ¶
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 ¶
Context returns a clone with the specified ctx for chained sub-operations.
func (*Browser) ControlURL ¶
ControlURL set the url to remote control browser.
func (*Browser) Decoding ¶ added in v0.125.0
Decoding selects how command results and events are decoded. It applies to the generated Call methods of the browser, its pages, and their elements, to Message.Load for the events the browser receives, and to the results and events that Rod decodes itself. The default, proto.DecodeStrict, rejects a result or event that lacks a field the protocol requires: the method that received it returns an error matching proto.ErrMissingField.
proto.DecodeLenient accepts such data, for endpoints that do not send complete protocol data. Missing and null fields then keep their zero value: objects and arrays are nil, a null entry of an array of objects or arrays is nil, and a null entry of another array, such as a node ID, is its zero value. Rod's methods check the objects, arrays and object entries that they use: instead of panicking or returning a nil result, a method whose result or event lacks one returns an error matching proto.ErrMissingField, a *proto.MissingFieldError that names the field as with proto.DecodeStrict. They also treat an empty identifier, or execution context ID 0, as missing where they would use it to address a browser context, target, session, search, script or execution context; for example, a page attached without a session ID would send its commands to the browser. Other missing fields keep their zero value, including IDs that events are matched by, and Rod's methods act on it as if the endpoint had sent it. Values that Rod returns or passes on, such as the node from Element.Describe and the events that handlers and Browser.Event receive, can still hold nil objects and entries, so your own code must check the fields it reads. Use lenient decoding only for an endpoint you trust to send what your code reads. Set it before Browser.Connect.
func (*Browser) DefaultDevice ¶
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. Requests follow the Browser.EnableDomain rules.
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, event decoding, 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. req is a domain enable command or Page.setLifecycleEventsEnabled; other requests return ErrUnsupportedDomain.
func (*Browser) Event ¶
Event subscribes to every browser event until the browser context or the connection ends. The stream is ordered, lossless, and unbounded: events that have not been read are kept in memory. Keep reading, or cancel the context given to Browser.Context, to release the subscription. Leaving a range loop early without canceling keeps the subscription and its growing backlog until that context or the connection ends.
func (*Browser) GetContext ¶
GetContext of current instance.
func (*Browser) GetCookies ¶
func (b *Browser) GetCookies() ([]*proto.NetworkCookie, error)
GetCookies from the browser.
func (*Browser) GetDecoding ¶ added in v0.125.0
GetDecoding returns the decoding set by Browser.Decoding. It implements proto.Decodable.
func (*Browser) HandleAuth ¶
func (b *Browser) HandleAuth(credentials AuthCredentials) func() error
HandleAuth answers the next HTTP authentication challenge whose source and origin match credentials, or whose source matches when credentials.AnyOrigin is set, then restores the previous Fetch configuration. Other challenges receive the browser's default response while the wait is active; headless Chrome fails those requests with net::ERR_INVALID_AUTH_CREDENTIALS rather than exposing the credentials. So does a challenge that proto.DecodeLenient leaves without its source, or without its origin when credentials.AnyOrigin is not set. Requests paused during the wait continue unmodified, so run at most one HandleAuth wait per browser and no other Fetch interception during it.
Call the returned wait function to handle authentication. It returns validation errors matching ErrAuthCredentials, 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 ¶
IgnoreCertErrors switch. If enabled, all certificate errors will be ignored.
func (*Browser) Launch ¶ added in v0.120.0
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 ¶
LoadState reports whether the last successful command of the method is retained. When method is a pointer, LoadState also replaces the value it points to with a copy decoded from the parameters that were sent. Only these commands are retained:
- Domain enable commands, such as Network.enable, until the domain's disable command.
- Page.setLifecycleEventsEnabled and Page.setInterceptFileChooserDialog.
- Emulation.setDeviceMetricsOverride, until Emulation.clearDeviceMetricsOverride.
- Browser.setDownloadBehavior, for each browser context. LoadState reads the setting of this Browser's context and ignores sessionID. It is removed when Target.disposeBrowserContext disposes the context.
Other commands are not retained. The retained commands of a session are removed when the session detaches, and all retained commands are removed when the browser connection ends. Use an empty sessionID for browser-level commands.
func (*Browser) Logger ¶
Logger overrides the default log functions for tracing and the monitor URL.
func (*Browser) Monitor ¶
Monitor address to listen if not empty. Shortcut for Browser.ServeMonitor. Browser.Connect logs the monitor URL, which includes its access token, as TraceTypeMonitor with the Browser.Logger. It then tries to open the URL in the system browser, passing it as a command-line argument that other users of the machine may be able to read. Call Browser.ServeMonitor instead to get the URL in code without opening it. Anyone who knows the URL can view the pages, so keep the monitor on loopback or protect it with a trusted authenticated proxy.
func (*Browser) MustConnect ¶
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(credentials AuthCredentials) (wait func())
MustHandleAuth is similar to Browser.HandleAuth.
func (*Browser) MustIgnoreCertErrors ¶
MustIgnoreCertErrors is similar to Browser.IgnoreCertErrors.
func (*Browser) MustIncognito ¶
MustIncognito is similar to Browser.Incognito.
func (*Browser) MustPage ¶
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 ¶
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 ¶
MustWaitDownload is similar to Browser.WaitDownload. Each call saves the download in a new temporary directory from os.MkdirTemp, which is private on Unix. The returned function reads the whole file into memory and removes that directory, including when the wait fails. Call it once to release the directory.
func (*Browser) NoDefaultDevice ¶
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. Concurrent calls for one target wait for a single attachment; if it fails, each waiter tries again. Different targets attach independently.
func (*Browser) Pages ¶
Pages retrieves visible pages. An incognito Browser returns only pages from its own browser context; the root Browser can enumerate every context.
func (*Browser) ServeMonitor ¶
ServeMonitor starts the monitor server and returns its URL. The reason why not to use "chrome://inspect/#devices" is one target cannot be driven by multiple controllers.
The returned URL ends with a random access token path; requests outside it get 404 Not Found. To block DNS rebinding, the Host header must name localhost, a loopback IP, the listener address, or the local address the request connected to; other requests get 403 Forbidden. Anyone who knows the URL can view the pages, so keep host on loopback or protect the monitor with a trusted authenticated proxy. launcher.Open passes the URL to the browser as a command-line argument, which other users of the machine may be able to read in the process list.
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 ¶
Sleeper returns a clone with the specified sleeper for chained sub-operations.
func (*Browser) SlowMotion ¶
SlowMotion set the delay for each control action, such as the simulation of the human inputs.
func (*Browser) Timeout ¶
Timeout returns a clone with the specified total timeout of all chained sub-operations.
func (*Browser) Trace ¶
Trace enables/disables the visual tracing of the input actions on the page. Trace logs and overlays omit typed text, character keys, and time or color input values.
func (*Browser) Version ¶
func (b *Browser) Version() (*proto.BrowserGetVersionResult, error)
Version info of the browser.
func (*Browser) WaitDownload ¶
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); use a directory that other local users cannot write, such as one from os.MkdirTemp. The wait returns an error matching ErrDownloadGUID, without the download, when the browser reports a GUID for that download that is not a single local file name. 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. Until the wait is invoked or the context ends, the subscription keeps target and download events in memory.
func (*Browser) WaitEvent ¶
WaitEvent loads the next matching event into out. E is a concrete protocol event type.
func (*Browser) WithCancel ¶
WithCancel returns a clone with a context cancel function.
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 DiagnosticLocation ¶ added in v0.120.0
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 Drag ¶ added in v0.122.0
type Drag struct {
// contains filtered or unexported fields
}
Drag is a native HTML drag with explicitly supplied CDP data. A Drag must not be copied. Call Drop or Cancel to finish it; canceling the originating page context also cancels it. Use a page context deadline to bound its lifetime.
func (*Drag) Cancel ¶ added in v0.122.0
Cancel ends the drag using an independent five-second cleanup context. It is safe to repeat, including after Drop, and returns any retained terminal error. Calling it after context cancellation waits for automatic cleanup to finish.
func (*Drag) Drop ¶ added in v0.122.0
Drop sends a final drag-over and drop at the last position, then releases the drag. If either command fails, it attempts cancellation within five seconds.
func (*Drag) MoveTo ¶ added in v0.122.0
MoveTo sends drag-over at position in main-frame viewport CSS pixels. An invalid position leaves the drag active; a protocol error cancels it.
func (*Drag) MustCancel ¶ added in v0.122.0
func (d *Drag) MustCancel()
MustCancel is similar to Drag.Cancel.
func (*Drag) MustDrop ¶ added in v0.122.0
func (d *Drag) MustDrop()
MustDrop is similar to Drag.Drop.
func (*Drag) MustMoveTo ¶ added in v0.122.0
MustMoveTo is similar to Drag.MoveTo.
type Element ¶
type Element struct {
Object *proto.RuntimeRemoteObject
// contains filtered or unexported fields
}
Element represents the DOM element.
func (*Element) Attribute ¶
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 ¶
BackgroundImage returns the css background-image of 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 ¶
CancelTimeout cancels the current timeout context and returns a clone with the parent context.
func (*Element) CanvasToImage ¶
CanvasToImage get image data of a canvas. The default format is image/png. The default quality is 0.92. A canvas without pixels yields empty data. A toDataURL result that is not a valid data URL returns an error wrapping ErrInvalidDataURL. 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 ¶
ContainsElement check if the target is equal or inside the element. A pseudo-element target belongs to its originating element.
func (*Element) Context ¶
Context returns a clone with the specified ctx for chained sub-operations.
func (*Element) Describe ¶
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) ElementByJS ¶
func (el *Element) ElementByJS(opts *EvalOptions) (*Element, error)
ElementByJS returns the element from the return value of the js.
func (*Element) ElementR ¶
ElementR returns the first child element that matches the css selector and its text matches the jsRegex.
func (*Element) ElementsByJS ¶
func (el *Element) ElementsByJS(opts *EvalOptions) (Elements, error)
ElementsByJS returns the elements from the return value of the js.
func (*Element) Eval ¶
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 ¶
Focus sets focus on the specified element. Before the action, it will try to scroll to the element.
func (*Element) Frame ¶
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 ¶
GetContext of current instance.
func (*Element) GetDecoding ¶ added in v0.125.0
GetDecoding returns the Browser.Decoding of the element's browser. It implements proto.Decodable.
func (*Element) GetSessionID ¶
func (el *Element) GetSessionID() proto.TargetSessionID
GetSessionID interface.
func (*Element) HasR ¶
HasR returns true if a child element that matches the css selector and its text matches the jsRegex.
func (*Element) Hover ¶
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 ¶
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 ¶
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 ¶
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 ¶
Interactable checks if the element is interactable with cursor. The cursor can be mouse, finger, stylus, etc. Pseudo-elements of the element or its descendants count as part of the element. 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) MoveMouseOut ¶
MoveMouseOut of the current element.
func (*Element) MustAttribute ¶
MustAttribute is similar to Element.Attribute.
func (*Element) MustBackgroundImage ¶
MustBackgroundImage is similar to Element.BackgroundImage.
func (*Element) MustBlur ¶
MustBlur is similar to Element.Blur.
func (*Element) MustCanvasToImage ¶
MustCanvasToImage is similar to Element.CanvasToImage.
func (*Element) MustClick ¶
MustClick is similar to Element.Click.
func (*Element) MustContainsElement ¶
MustContainsElement is similar to Element.ContainsElement.
func (*Element) MustDescribe ¶
MustDescribe is similar to Element.Describe.
func (*Element) MustDisabled ¶
MustDisabled is similar to Element.Disabled.
func (*Element) MustDoubleClick ¶
MustDoubleClick is similar to Element.Click.
func (*Element) MustElement ¶
MustElement is similar to Element.Element.
func (*Element) MustElementByJS ¶
MustElementByJS is similar to Element.ElementByJS.
func (*Element) MustElementR ¶
MustElementR is similar to Element.ElementR.
func (*Element) MustElementX ¶
MustElementX is similar to Element.ElementX.
func (*Element) MustElements ¶
MustElements is similar to Element.Elements.
func (*Element) MustElementsByJS ¶
MustElementsByJS is similar to Element.ElementsByJS.
func (*Element) MustElementsX ¶
MustElementsX is similar to Element.ElementsX.
func (*Element) MustEqual ¶
MustEqual is similar to Element.Equal.
func (*Element) MustEval ¶
MustEval is similar to Element.Eval.
func (*Element) MustFocus ¶
MustFocus is similar to Element.Focus.
func (*Element) MustFrame ¶
MustFrame is similar to Element.Frame.
func (*Element) MustGetXPath ¶
MustGetXPath is similar to Element.GetXPath.
func (*Element) MustHTML ¶
MustHTML is similar to Element.HTML.
func (*Element) MustHas ¶
MustHas is similar to Element.Has.
func (*Element) MustHasR ¶
MustHasR is similar to Element.HasR.
func (*Element) MustHasX ¶
MustHasX is similar to Element.HasX.
func (*Element) MustHover ¶
MustHover is similar to Element.Hover.
func (*Element) MustInput ¶
MustInput is similar to Element.Input.
func (*Element) MustInputColor ¶
MustInputColor is similar to Element.InputColor.
func (*Element) MustInputTime ¶
MustInputTime is similar to Element.Input.
func (*Element) MustInteractable ¶
MustInteractable is similar to Element.Interactable.
func (*Element) MustKeyActions ¶
func (el *Element) MustKeyActions() *KeyActions
MustKeyActions is similar to Element.KeyActions.
func (*Element) MustMatches ¶
MustMatches is similar to Element.Matches.
func (*Element) MustMoveMouseOut ¶
MustMoveMouseOut is similar to Element.MoveMouseOut.
func (*Element) MustNext ¶
MustNext is similar to Element.Next.
func (*Element) MustParent ¶
MustParent is similar to Element.Parent.
func (*Element) MustParents ¶
MustParents is similar to Element.Parents.
func (*Element) MustPrevious ¶
MustPrevious is similar to Element.Previous.
func (*Element) MustProperty ¶
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 ¶
MustResource is similar to Element.Resource.
func (*Element) MustScreenshot ¶
MustScreenshot is similar to Element.Screenshot.
func (*Element) MustScrollIntoView ¶
MustScrollIntoView is similar to Element.ScrollIntoView.
func (*Element) MustSelect ¶
MustSelect is similar to Element.Select.
func (*Element) MustSelectAllText ¶
MustSelectAllText is similar to Element.SelectAllText.
func (*Element) MustSelectText ¶
MustSelectText is similar to Element.SelectText.
func (*Element) MustSetFiles ¶
MustSetFiles is similar to Element.SetFiles.
func (*Element) MustSetFilesFromMemory ¶ added in v0.122.0
func (el *Element) MustSetFilesFromMemory(files ...FilePayload) *Element
MustSetFilesFromMemory is similar to Element.SetFilesFromMemory.
func (*Element) MustShadowRoot ¶
MustShadowRoot is similar to Element.ShadowRoot.
func (*Element) MustShape ¶
func (el *Element) MustShape() *proto.DOMGetContentQuadsResult
MustShape is similar to Element.Shape.
func (*Element) MustText ¶
MustText is similar to Element.Text.
func (*Element) MustType ¶
MustType is similar to Element.Type.
func (*Element) MustVisible ¶
MustVisible is similar to Element.Visible.
func (*Element) MustWait ¶
MustWait is similar to Element.Wait.
func (*Element) MustWaitEnabled ¶
MustWaitEnabled is similar to Element.WaitEnabled.
func (*Element) MustWaitInteractable ¶
MustWaitInteractable is similar to Element.WaitInteractable.
func (*Element) MustWaitInvisible ¶
MustWaitInvisible is similar to Element.WaitInvisible..
func (*Element) MustWaitLoad ¶
MustWaitLoad is similar to Element.WaitLoad.
func (*Element) MustWaitStable ¶
MustWaitStable is similar to Element.WaitStable.
func (*Element) MustWaitVisible ¶
MustWaitVisible is similar to Element.WaitVisible.
func (*Element) MustWaitWritable ¶
MustWaitWritable is similar to Element.WaitWritable.
func (*Element) Property ¶
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 ¶
Release is a shortcut for Page.Release current element.
func (*Element) Resource ¶
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 ¶
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 ¶
SelectAllText selects all text Before the action, it will try to scroll to the element and focus on it.
func (*Element) SelectText ¶
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 ¶
SetFiles sets the current file input's files using paths on the browser's host. Relative paths are made absolute on the client; no file content is transferred. Use Element.SetFilesFromMemory to supply bytes to a local or remote browser.
func (*Element) SetFilesFromMemory ¶ added in v0.122.0
func (el *Element) SetFilesFromMemory(files []FilePayload) error
SetFilesFromMemory replaces the current file input's files with the supplied names, MIME types, and bytes, transferred through the existing CDP connection. A nil or empty list clears the selection. More than one file requires a multiple input; non-file inputs or invalid file counts return EvalError without changing files. After assignment, it dispatches bubbling input and change events. These events are synthetic (isTrusted is false); no native file chooser is opened.
func (*Element) ShadowRoot ¶
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 ¶
Sleeper returns a clone with the specified sleeper for chained sub-operations.
func (*Element) Tap ¶
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) Timeout ¶
Timeout returns a clone with the specified total timeout of all chained sub-operations.
func (*Element) Type ¶
Type is similar with Keyboard.Type. Before the action, it will try to scroll to the element and focus on it.
func (*Element) Wait ¶
func (el *Element) Wait(opts *EvalOptions) error
Wait until the js returns true.
func (*Element) WaitEnabled ¶
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 ¶
WaitInteractable waits for the element to be interactable. It will try to scroll to the element on each try.
func (*Element) WaitInvisible ¶
WaitInvisible until the element invisible.
func (*Element) WaitStable ¶
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 ¶
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 ¶
WaitVisible until the element is visible.
func (*Element) WaitWritable ¶
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 ¶
WithCancel returns a clone with a context cancel function.
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.
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) This ¶
func (e *EvalOptions) This(obj *proto.RuntimeRemoteObject) *EvalOptions
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. An event that cannot be decoded as E, including one that lacks a field the protocol requires (see Message.Load), ends the wait, which returns the decoding error.
type ExpectElementError ¶
type ExpectElementError struct {
*proto.RuntimeRemoteObject
}
ExpectElementError error.
func (*ExpectElementError) Error ¶
func (e *ExpectElementError) Error() string
type ExpectElementsError ¶
type ExpectElementsError struct {
*proto.RuntimeRemoteObject
}
ExpectElementsError error.
func (*ExpectElementsError) Error ¶
func (e *ExpectElementsError) Error() string
type FilePayload ¶ added in v0.122.0
type FilePayload struct {
// Name is the filename supplied to the browser's File constructor.
Name string `json:"name"`
// MIMEType is the file's media type, normalized by the browser's File constructor.
MIMEType string `json:"mimeType"`
// Data is the file's content. Nil and empty slices both create an empty file.
Data []byte `json:"data"`
}
FilePayload is a file supplied from memory to Element.SetFilesFromMemory.
type Hijack ¶
type Hijack struct {
Request *HijackRequest
Response *HijackResponse
// OnError receives errors resolving this request and recovered handler
// panics. It starts as the router's OnError handler; nil also reports there.
OnError func(error)
// Skip to next handler
Skip bool
// MaxResponseBodyBytes limits the body that LoadResponse reads. It starts at
// DefaultMaxResponseBodyBytes; zero or a negative value selects that default.
// Fulfilling a body larger than about 74 MiB, or less with large headers,
// exceeds Chrome's DevTools message limit and closes the connection.
MaxResponseBodyBytes int64
// MaxResponseHeaderBytes limits the response headers that LoadResponse
// applies, counted as an HTTP/1.1 header block: each value adds the length
// of its name and value plus four bytes. It starts at
// DefaultMaxResponseHeaderBytes; zero or a negative value selects that
// default. A higher limit lets LoadResponse apply headers that Chrome
// rejects from the network. The headers and the base64 encoded body reach
// Chrome in one message, and a message larger than 100 MiB closes the
// DevTools connection. The client's transport applies its own limit first;
// http.Transport allows 10 MiB by default.
MaxResponseHeaderBytes int64
// FollowRedirects makes LoadResponse follow redirects in Go, using the
// client's CheckRedirect policy, or http.Client's default policy of at most
// 10 redirects when the client has none. The final response then fulfills
// the original request, and headers of the redirect responses, such as
// Set-Cookie, do not reach the browser. It starts false: LoadResponse
// returns a 3xx response to the browser, which follows it under its own
// policies.
//
// Following redirects in Go gives the page the final response as the
// response of the original URL. A page whose request is redirected, such
// as by its own server or an open redirect, can then read the response of
// any URL the client can reach, including internal services, as
// same-origin data; the browser's CORS and private network protections do
// not apply. The final response's headers, such as Set-Cookie,
// Content-Security-Policy, and CORS headers, also apply to the original
// URL, so a redirect target can set cookies for the page's origin. Go also
// forwards the request headers to every redirect target, including custom
// headers such as API tokens. It drops Authorization, Cookie, and the other
// credential headers that net/http removes only when the target host is
// neither the original host nor one of its subdomains, so they reach
// subdomains and other ports and schemes of the same host, including plain
// http. When the
// original request has a Referer, Go sends it unchanged to each target;
// otherwise it sends the previous URL, with its path and query, as the
// Referer, except on a redirect from https to http. Enable it only for
// requests whose redirect targets you trust, or give the client a
// CheckRedirect that rejects other targets and removes the headers they
// must not receive.
FollowRedirects 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 ¶
LoadResponse sends the request with client and loads the response as the default response to override. A nil client uses http.DefaultClient.
Unless FollowRedirects is set, redirects are not followed. A 3xx response and its Location header return to the browser, which follows the redirect under its own CORS and network policies; routes intercept the next request again, and the client's CheckRedirect is not used. The request is sent by Go, so it uses the client's transport, proxy, and TLS settings and bypasses the browser's proxy configuration and private network protections.
Response headers larger than MaxResponseHeaderBytes return an error matching ErrResponseHeadersTooLarge. With loadBody, a body larger than MaxResponseBodyBytes returns an error matching ErrResponseBodyTooLarge. Responses to HEAD requests and 1xx, 204, and 304 responses load an empty body whatever their Content-Length. The status, headers, and body are applied only after the response loads successfully.
func (*Hijack) MustLoadResponse ¶
func (h *Hijack) MustLoadResponse()
MustLoadResponse is similar to Hijack.LoadResponse with http.DefaultClient, loading the body. It uses the Hijack's FollowRedirects setting and size limits.
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) 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 ¶
func (ctx *HijackRequest) Type() proto.NetworkResourceType
Type of the resource.
func (*HijackRequest) URL ¶
func (ctx *HijackRequest) URL() *url.URL
URL of the request. It is never nil: handlers never run for requests whose URL net/url cannot parse. The router fails those requests or, with HijackRouter.ContinueUnparsableURLs, continues them.
type HijackResponse ¶
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) Fail ¶
func (ctx *HijackResponse) Fail(reason proto.NetworkErrorReason) *HijackResponse
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.
Each paused request is served on its own goroutine, so handlers run concurrently. The router resolves every paused request once. If a handler panics, including through a Must helper such as Hijack.MustLoadResponse, or ends its goroutine with runtime.Goexit, the router fails the request with net::ERR_FAILED and reports a *TryError or ErrHijackHandlerExited through the request's OnError. The browser request URL is parsed with net/url. The router does not run handlers for a request whose URL it cannot parse: it fails the request, or continues it unmodified when ContinueUnparsableURLs is enabled, and reports the parse error through the router's OnError. With proto.DecodeLenient, a paused request can lack its request details; the router fails it without running handlers and reports an error matching proto.ErrMissingField through the router's OnError.
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) ContinueUnparsableURLs ¶ added in v0.125.0
func (r *HijackRouter) ContinueUnparsableURLs(enabled bool) *HijackRouter
ContinueUnparsableURLs sets whether the router continues, unmodified, the paused requests whose URL net/url cannot parse, such as a path with a stray '%' like "/sale-50%-off" or a host name containing '{'. By default the router fails them with net::ERR_FAILED. Either way, no handler runs for them, and the parse error goes to the router's OnError. It applies to later requests.
Enabling it lets a page evade routes: a URL with an invalid percent escape, such as "/api/users%zz", or with such a host name still matches a route's pattern but reaches the network without the blocking, mocking, or rewriting that the route would apply. Enable it only when no route enforces a policy that the page must not evade.
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) OnError ¶ added in v0.125.0
func (r *HijackRouter) OnError(fn func(error)) *HijackRouter
OnError sets the router's error handler. It is the initial Hijack.OnError of each later request and receives errors for requests the router resolves without running handlers, such as a URL that net/url cannot parse. It is called concurrently from the goroutines serving requests. A nil fn discards errors.
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.
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 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) 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 ¶
MustType is similar to Keyboard.Type.
func (*Keyboard) Press ¶
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.
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 ¶
Load decodes a matching event into out and reports whether out holds it. E is the concrete protocol event type. A message for another method returns false and a nil error. When the method matches but the parameters cannot be decoded as E, Load returns false and the decoding error, leaving out unchanged. Parameters are decoded with the Browser.Decoding of the browser that received the event, proto.DecodeStrict by default, which returns an error that wraps *proto.MissingFieldError for an event that lacks a field the protocol requires. 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 ¶
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 ¶
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) 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 ¶
MustMoveTo is similar to [Mouse.Move].
func (*Mouse) MustScroll ¶
MustScroll is similar to Mouse.Scroll.
func (*Mouse) MustUp ¶
func (m *Mouse) MustUp(button proto.InputMouseButton) *Mouse
MustUp is similar to Mouse.Up.
type NavigationError ¶
type NavigationError struct {
}
NavigationError error.
func (*NavigationError) Error ¶
func (e *NavigationError) Error() string
type NoPointerEventsError ¶
type NoPointerEventsError struct {
*Element
}
NoPointerEventsError error.
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
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) AddScriptTag ¶
AddScriptTag to page. If url is empty, content will be used.
func (*Page) AddStyleTag ¶
AddStyleTag to page. If url is empty, content will be used.
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 ¶
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) Context ¶
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 ¶
DisableDomain temporarily disables a domain and returns an idempotent function that restores its previous configuration, including after caller cancellation.
func (*Page) Drag ¶ added in v0.122.0
Drag enters a native HTML drag at position in the main frame's viewport, in CSS pixels. Use a top-level page and supply text, HTML, or link drag data. File drags are unsupported. Data is copied, and each event uses the page's currently held keyboard modifiers. This does not synthesize dragstart, press mouse buttons, move the mouse, or change drag interception settings. Only one Drag may be active per page session. Defer Cancel after success.
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 ¶
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. A non-null result that is not a DOM node is released before ExpectElementError is returned; the error describes the value.
func (*Page) ElementFromNode ¶
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. An object without an id returns ExpectElementError.
func (*Page) ElementFromPoint ¶
ElementFromPoint creates an Element from the absolute point on the page. The point should include the window scroll offset.
func (*Page) ElementR ¶
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 ¶
ElementX retries until an element in the page that matches one of the XPath selectors, then returns the matched element.
func (*Page) ElementsByJS ¶
func (p *Page) ElementsByJS(opts *EvalOptions) (Elements, error)
ElementsByJS returns the elements from the return value of the js. Handles that are not returned in an element are released, including the result when ExpectElementsError is returned; the error describes the value.
func (*Page) Emulate ¶
Emulate the device, such as iPhone9. If device is devices.Clear, it will clear the override.
func (*Page) EnableDomain ¶
EnableDomain shares enablement until its idempotent restore function is called. Setup and bounded restoration errors are returned to the caller. Requests follow the Browser.EnableDomain rules.
func (*Page) Eval ¶
Eval is a shortcut for Page.Evaluate with AwaitPromise, ByValue set to true.
func (*Page) EvalJSON ¶ added in v0.120.0
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 ¶
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 ¶
Event subscribes to this page's session events until the page context or its session ends. The stream is ordered, lossless, and unbounded: events that have not been read are kept in memory. Keep reading, or cancel the context given to Page.Context, to release the subscription. Leaving a range loop early without canceling keeps the subscription and its growing backlog until that context or the session ends.
func (*Page) Expose ¶
func (p *Page) Expose(name string, fn func(jsonvalue.Value) (any, error), onError func(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. If fn or the encoding of its result panics, or fn ends its goroutine with runtime.Goexit, such as through a failing Must helper, the promise rejects with the message "exposed function failed" and later calls are still handled. The page does not receive the panic value. A non-nil onError receives the errors of calls that fn did not return: a *TryError holding the panic value, ErrExposedFunctionExited for runtime.Goexit, and an error wrapping the encoding error of a result that cannot be JSON-encoded. onError runs on the goroutine that calls fn, after the call's reply is queued, so later calls wait for it. A panic in onError is not recovered. Calls run fn one at a time in the order the page made them, and replies reach the page in that order. fn can start the next call before the page receives the previous reply. Replies that wait for the page are delivered in batches, so several promises can resolve in the same task. Calls that fn has not handled and replies that the page has not received, including fn's encoded results, stay in this process's memory until then, so a page that keeps making calls faster than it receives the replies increases memory use. 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 ¶
ExposeHelpers installs the helper functions in list and assigns Rod's helper functions to window.rod in the page's main world, so that they can be debugged in the DevTools console. Page scripts can then replace the helpers that Rod calls in that document; do not use it on untrusted pages.
func (*Page) GetContext ¶
GetContext of current instance.
func (*Page) GetDecoding ¶ added in v0.125.0
GetDecoding returns the Browser.Decoding of the page's browser. It implements proto.Decodable.
func (*Page) GetNavigationHistory ¶
func (p *Page) GetNavigationHistory() (*proto.PageGetNavigationHistoryResult, error)
GetNavigationHistory get navigation history.
func (*Page) GetResource ¶
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) 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 ¶
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) HasR ¶
HasR an element that matches the css selector and its display text matches the jsRegex.
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 ¶
InsertText is like pasting text into the page.
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 ¶
LoadState loads the page session's retained command into method, following the Browser.LoadState rules.
func (*Page) MustActivate ¶
MustActivate is similar to Page.Activate.
func (*Page) MustAddScriptTag ¶
MustAddScriptTag is similar to Page.AddScriptTag.
func (*Page) MustAddStyleTag ¶
MustAddStyleTag is similar to Page.AddStyleTag.
func (*Page) MustCaptureDOMSnapshot ¶
func (p *Page) MustCaptureDOMSnapshot() (domSnapshot *proto.DOMSnapshotCaptureSnapshotResult)
MustCaptureDOMSnapshot is similar to Page.CaptureDOMSnapshot.
func (*Page) MustCookies ¶
func (p *Page) MustCookies(urls ...string) []*proto.NetworkCookie
MustCookies is similar to Page.Cookies.
func (*Page) MustElement ¶
MustElement is similar to Page.Element.
func (*Page) MustElementByJS ¶
MustElementByJS is similar to Page.ElementByJS.
func (*Page) MustElementFromNode ¶
MustElementFromNode is similar to Page.ElementFromNode.
func (*Page) MustElementFromPoint ¶
MustElementFromPoint is similar to Page.ElementFromPoint.
func (*Page) MustElementR ¶
MustElementR is similar to Page.ElementR.
func (*Page) MustElementX ¶
MustElementX is similar to Page.ElementX.
func (*Page) MustElements ¶
MustElements is similar to Page.Elements.
func (*Page) MustElementsByJS ¶
MustElementsByJS is similar to Page.ElementsByJS.
func (*Page) MustElementsX ¶
MustElementsX is similar to Page.ElementsX.
func (*Page) MustEmulate ¶
MustEmulate is similar to Page.Emulate.
func (*Page) MustEvalOnNewDocument ¶
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), onError func(error)) (stop func())
MustExpose is similar to Page.Expose.
func (*Page) MustExposeHelpers ¶ added in v0.125.0
MustExposeHelpers is similar to Page.ExposeHelpers.
func (*Page) MustGetWindow ¶
func (p *Page) MustGetWindow() *proto.BrowserBounds
MustGetWindow is similar to Page.GetWindow.
func (*Page) MustHandleDialog ¶
func (p *Page) MustHandleDialog() (wait func() *proto.PageJavascriptDialogOpening, handle func(bool, string))
MustHandleDialog is similar to Page.HandleDialog.
func (*Page) MustHandleFileDialog ¶
MustHandleFileDialog is similar to Page.HandleFileDialog.
func (*Page) MustInfo ¶
func (p *Page) MustInfo() *proto.TargetTargetInfo
MustInfo is similar to Page.Info.
func (*Page) MustInsertText ¶
MustInsertText is similar to Page.InsertText.
func (*Page) MustNavigate ¶
MustNavigate is similar to Page.Navigate.
func (*Page) MustNavigateBack ¶
MustNavigateBack is similar to Page.NavigateBack.
func (*Page) MustNavigateForward ¶
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 ¶
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) MustResetNavigationHistory ¶
MustResetNavigationHistory is similar to Page.ResetNavigationHistory.
func (*Page) MustScreenshot ¶
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 ¶
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 ¶
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 ¶
MustSearch is similar to Page.Search. It only returns the first element in the search result.
func (*Page) MustSetBlockedURLs ¶
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 ¶
MustSetDocumentContent is similar to Page.SetDocumentContent.
func (*Page) MustSetExtraHeaders ¶
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 ¶
MustSetViewport is similar to Page.SetViewport.
func (*Page) MustSetWindow ¶
MustSetWindow is similar to Page.SetWindow.
func (*Page) MustStopLoading ¶
MustStopLoading is similar to Page.StopLoading.
func (*Page) MustTriggerFavicon ¶
MustTriggerFavicon is similar to [PageTriggerFavicon].
func (*Page) MustWaitDOMStable ¶
MustWaitDOMStable is similar to Page.WaitDOMStable.
func (*Page) MustWaitElementsMoreThan ¶
MustWaitElementsMoreThan is similar to Page.WaitElementsMoreThan.
func (*Page) MustWaitIdle ¶
MustWaitIdle is similar to Page.WaitIdle.
func (*Page) MustWaitInteractive ¶ added in v0.122.0
MustWaitInteractive is similar to Page.WaitInteractive.
func (*Page) MustWaitLoad ¶
MustWaitLoad is similar to Page.WaitLoad.
func (*Page) MustWaitNavigation ¶
func (p *Page) MustWaitNavigation() func()
MustWaitNavigation is similar to Page.WaitNavigation.
func (*Page) MustWaitOpen ¶
MustWaitOpen is similar to Page.WaitOpen.
func (*Page) MustWaitRequestIdle ¶
MustWaitRequestIdle is similar to Page.WaitRequestIdle.
func (*Page) MustWaitStable ¶
MustWaitStable is similar to Page.WaitStable.
func (*Page) MustWindowFullscreen ¶
MustWindowFullscreen is similar to [Page.WindowFullscreen].
func (*Page) MustWindowMaximize ¶
MustWindowMaximize is similar to [Page.WindowMaximize].
func (*Page) MustWindowMinimize ¶
MustWindowMinimize is similar to [Page.WindowMinimize].
func (*Page) MustWindowNormal ¶
MustWindowNormal is similar to [Page.WindowNormal].
func (*Page) Navigate ¶
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) ObjectToJSON ¶
ObjectToJSON by object id.
func (*Page) Overlay ¶
Overlay a rectangle on the main frame with specified message. The message is displayed as plain text.
func (*Page) PDF ¶
func (p *Page) PDF(req *proto.PagePrintToPDF) (*StreamReader, error)
PDF prints page as PDF. The returned reader's ChunkSize is 4 MiB.
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) ResetNavigationHistory ¶
ResetNavigationHistory reset history.
func (*Page) Screenshot ¶
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 ¶
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 ¶
SetDocumentContent sets the page document html content.
func (*Page) SetExtraHeaders ¶
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 ¶
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 ¶
StopLoading forces the page stop navigation and pending resource fetches.
func (*Page) Timeout ¶
Timeout returns a clone with the specified total timeout of all chained sub-operations.
func (*Page) TriggerFavicon ¶
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) WaitDOMStable ¶
WaitDOMStable waits until the DOM of the page's document stays stable for d. A mutation observer inside the page records changes, while Rod times the period and checks the observer through the protocol. Each check exchanges less than a kilobyte regardless of the DOM size: one check suffices when the DOM is stable, and changes cost one check per period. The period does not depend on page timers, so the wait works in background tabs.
Changes are counted in nodes, each at most once per period. An inserted or removed node counts with its descendants, and a node whose attributes or character data change counts once. A change that a script undoes before the observer receives it, such as a node inserted and removed again in one task, or an attribute or text restored to its previous value, is not a change. The DOM is stable when the nodes changed during d number at most diff times the nodes present when observation of the document began. A change beyond that limit restarts the period. diff is a fraction from 0 to 1; 0 requires d without any change.
A page with scripts disabled cannot deliver the observer's records. Each check then compares a digest of the DOM with the previous one, which costs time proportional to the DOM size, and any change restarts the period regardless of diff.
The wait observes the document and its open shadow roots. It observes the shadow roots of inserted elements immediately, and finds a shadow root attached to an element already in the document when the period would end, which restarts the period. It does not observe iframe documents or closed shadow roots; use Element.Frame to wait for a frame. State that the DOM tree does not reflect, such as form control values or animations, is not a change. When navigation replaces the document, a new period begins in its successor. When the context ends, the wait returns at once and removes its observer from the page separately. d is the stable time, not a timeout; bound the wait with Page.Timeout or a context deadline.
func (*Page) WaitElementsMoreThan ¶
WaitElementsMoreThan waits until there are more than num elements that match the selector.
func (*Page) WaitEvent ¶
WaitEvent loads the next matching event into out. E is a concrete protocol event type.
func (*Page) WaitInteractive ¶ added in v0.122.0
WaitInteractive waits until the document is parsed (readyState is interactive or complete). It does not wait for images, asynchronous application work, or DOM stability. If navigation replaces the document, it waits for the new document. Use Page.WaitLoad for full load or Page.WaitDOMStable for DOM stability.
func (*Page) WaitLoad ¶
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 ¶
WaitOpen waits for the next new page opened by the current one. The wait ends if the opener's session ends. The returned page uses the caller's operation context independently of the opener's session and the wait's cleanup.
func (*Page) WaitRepaint ¶
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 ¶
WaitStable waits until the page is stable for d duration.
func (*Page) WithCancel ¶
WithCancel returns a clone with a context cancel function.
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
func (d *PageDiagnostics) Stop() (DiagnosticsSnapshot, error)
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, as does an event that was skipped because it could not be decoded or lacked an object that the diagnostics use, such as the exception details that proto.DecodeLenient can leave missing. 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) MustFindByURL ¶
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 (Pool[T]) Get ¶
Get a elem from the pool, allow error. Use the [Pool[T].Put] to make it reusable later.
type RaceContext ¶
type RaceContext struct {
// contains filtered or unexported fields
}
RaceContext stores the branches to 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.
// FixedTop and FixedBottom must be nonnegative, and together smaller than
// the viewport height.
FixedBottom float64
// WaitPerScroll is the DOM stability period after each scroll, passed to
// [Page.WaitDOMStable] (default is 300ms). It must not be negative.
WaitPerScroll time.Duration
// MaxHeight (optional) is the tallest page content, in CSS pixels, to
// capture. Taller content returns [ErrScrollScreenshotTooTall] before any
// capture. It must be positive. Default is 32768.
MaxHeight float64
}
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) 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 the stream position of the next byte Read returns.
// Read advances it by the number of bytes returned. Assigning Offset or
// changing its value before a Read discards buffered data and reads from there.
Offset *int
// ChunkSize is the minimum number of bytes each IO.read requests. Read
// requests the larger of ChunkSize and len(p) and keeps data beyond p for
// later reads, saving round trips for small buffers. The browser answers at
// once for complete data, such as PDF output or a blob, but for a response
// body still loading, such as a Fetch.takeResponseBodyAsStream stream, only
// when the requested size arrives or the body ends. Each response encodes up
// to the requested size as base64 in one CDP message. Zero requests len(p).
ChunkSize 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.
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) 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 ¶
MustCancel is similar to Touch.Cancel.
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.
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" // TraceTypeMonitor type logs the URL of the monitor that [Browser.Monitor] starts. TraceTypeMonitor TraceType = "monitor" )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
browser-response
command
Run with: go run ./examples/browser-response Capture the browser's authenticated POST response without replaying the request.
|
Run with: go run ./examples/browser-response Capture the browser's authenticated POST response without replaying the request. |
|
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. |
|
drag
command
Run with: go run ./examples/drag Deliver a native HTML drag payload to a drop target on a local page.
|
Run with: go run ./examples/drag Deliver a native HTML drag payload to a drop target on a local page. |
|
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 |
|
load-extension
command
Run from the repository root with: go run ./examples/load-extension Load an unpacked Manifest V3 extension and observe its content script on a local page.
|
Run from the repository root with: go run ./examples/load-extension Load an unpacked Manifest V3 extension and observe its content script on a local page. |
|
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 |
|
persistent-profile
command
Run with: go run ./examples/persistent-profile -profile /path/to/rod-automation-profile Use a dedicated non-default profile.
|
Run with: go run ./examples/persistent-profile -profile /path/to/rod-automation-profile Use a dedicated non-default profile. |
|
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. |
|
query-selection
command
Run with: go run ./examples/query-selection Compare query choices and bound required waits on a local HTTP fixture.
|
Run with: go run ./examples/query-selection Compare query choices and bound required waits on a local HTTP fixture. |
|
screencast
command
Run with: go run ./examples/screencast -out /tmp/screencast.tar Record a local animation and its pauses as timestamped PNG frames.
|
Run with: go run ./examples/screencast -out /tmp/screencast.tar Record a local animation and its pauses as timestamped PNG frames. |
|
tab-metadata
command
Run with: go run ./examples/tab-metadata Read tab metadata without activating tabs.
|
Run with: go run ./examples/tab-metadata Read tab metadata without activating tabs. |
|
typing
command
Run with: go run ./examples/typing
|
Run with: go run ./examples/typing |
|
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/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. |
