Skip to content

Contexts and the browser

A chromedp program keeps its browser in a context.Context. The context says which browser and which tab an action runs on, and when they stop.

ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()

chromedp.NewContext makes the context. It does not start Chrome. The first call of chromedp.Run or chromedp.Do on the context starts Chrome and opens a tab. cancel closes the tab and stops Chrome. Call it with defer, or Chrome can keep running after the program ends.

A context that you make from a chromedp context uses the same browser, and its first call opens a new tab:

tab, cancelTab := chromedp.NewContext(ctx)
defer cancelTab()

Actions on one context run in one tab. Two goroutines can drive two tabs at the same time, each with its own context. cancelTab closes only the tab.

The first call on a context starts the browser, and the browser lives as long as the context of that call. So a timeout on the context of the first call also stops the browser when it ends. That is right for a short program, such as the tutorials of this site. To limit one action of a longer program, start the browser first, then derive the timeout from the context:

// The empty Do starts the browser on ctx, which has no timeout.
if err := chromedp.Do(ctx); err != nil {
	return err
}

// The timeout limits only this action.
tctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
text, err := chromedp.Run(tctx, chromedp.Text(chromedp.CSS("#result")))

chromedp.NewExecAllocator sets how chromedp starts Chrome. Start from chromedp.DefaultExecAllocatorOptions, and add or change options:

opts := append(chromedp.DefaultExecAllocatorOptions[:],
	chromedp.ExecPath("/usr/bin/chromium"),
	chromedp.WindowSize(1280, 800),
	chromedp.Flag("lang", "de"),
)
allocCtx, cancelAlloc := chromedp.NewExecAllocator(context.Background(), opts...)
defer cancelAlloc()

ctx, cancel := chromedp.NewContext(allocCtx)
defer cancel()

Chrome runs headless by default, with no window. To see the window, add the option chromedp.WithVisibleWindow() to chromedp.NewContext, or set the environment variable CHROMEDP_VISIBLEWINDOW=1 with no change in the code.

The option chromedp.WithDebugf(log.Printf) of chromedp.NewContext prints each message between the program and Chrome. The recordings of this site show the same messages.