Skip to content

Actions

An action is one step on a tab, such as a click or a read of the page. chromedp runs actions with chromedp.Run and chromedp.Do.

chromedp.Run runs one action and returns its value and an error:

title, err := chromedp.Run(ctx, chromedp.Title())

The type of the value comes from the action: chromedp.Title returns a string, chromedp.Nodes returns the nodes that a selector finds, and chromedp.Screenshot returns the bytes of an image.

chromedp.Do runs actions that return no value, in order. It stops at the first error:

err := chromedp.Do(ctx,
	chromedp.Navigate(url),
	chromedp.Click(chromedp.CSS("#greet")),
)

chromedp.Steps joins actions into one action. A function that returns chromedp.Steps(...) gives a name to a sequence of steps that a program uses more than once.

chromedp.Evaluate runs JavaScript in the page and decodes its result into the type that you name:

n, err := chromedp.Run(ctx, chromedp.Evaluate[int](`document.querySelectorAll("li").length`))

chromedp.Sleep waits for a time. Prefer an action that waits for the page, such as chromedp.WaitVisible or chromedp.Poll, because a page does not always take the same time. See Selectors and waiting.

An action of chromedp is a sequence of commands of the Chrome DevTools Protocol. The package github.com/chromedp/cdproto has every command, event and type of the protocol. chromedp.Call sends one command to the tab and returns its result:

import (
	"github.com/chromedp/cdproto/cdp"
	"github.com/chromedp/cdproto/page"
)

// A command with no parameters takes cdp.Empty{}.
layout, err := chromedp.Call(ctx, page.GetLayoutMetrics, cdp.Empty{})

chromedp.CallBrowser sends a command to the browser and not to a tab. The tutorial Intercept requests sends commands of the Fetch domain this way. The documentation of the protocol lists the domains.

An action is a function. chromedp.Func makes an action from a function that returns an error:

scrollToEnd := chromedp.Func(func(ctx context.Context, t *chromedp.Target) error {
	_, err := chromedp.Call(ctx, input.DispatchKeyEvent, input.DispatchKeyEventParams{
		Type: input.DispatchKeyEventTypeKeyDown,
		Key:  "End",
	})
	return err
})