# Contexts and the browser

> How a chromedp context holds a browser and a tab, when Chrome starts and stops, and how to set a timeout.

The page: https://chromedp.dev/concepts/contexts/

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.

## Start and stop the browser

```go
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.

## Tabs

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

```go
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.

## Timeouts

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:

```go
// 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")))
```

## Options of the browser

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

```go
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.

## Log the protocol

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.
