Appearance
Usage
Minimal example: navigate and read the page title
This is the canonical starter program. It opens a new headless Chrome context, navigates to example.com, reads the page title, and prints it.
go
package main
import (
"context"
"fmt"
"log"
"github.com/chromedp/chromedp"
)
func main() {
// Create a new chromedp context (launches Chrome in headless mode).
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
// Run a sequence of actions.
var title string
if err := chromedp.Run(ctx,
chromedp.Navigate("https://example.com"),
chromedp.Title(&title),
); err != nil {
log.Fatal(err)
}
fmt.Println("Page title:", title)
}Expected output:
Page title: Example DomainScreenshot example
Capture a full-page screenshot and save it to disk.
go
package main
import (
"context"
"log"
"os"
"github.com/chromedp/chromedp"
)
func main() {
ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
var buf []byte
if err := chromedp.Run(ctx,
chromedp.Navigate("https://example.com"),
chromedp.FullScreenshot(&buf, 90),
); err != nil {
log.Fatal(err)
}
if err := os.WriteFile("screenshot.png", buf, 0644); err != nil {
log.Fatal(err)
}
}Core action types
| Action | What it does |
|---|---|
chromedp.Navigate(url) | Load a URL in the browser |
chromedp.Title(&s) | Read the current page title into s |
chromedp.Text(sel, &s) | Read text content of a CSS selector |
chromedp.Click(sel) | Click a DOM element |
chromedp.SendKeys(sel, keys) | Type into an input field |
chromedp.Screenshot(sel, &buf) | Screenshot a specific element |
chromedp.FullScreenshot(&buf, quality) | Screenshot the full viewport |
chromedp.Evaluate(js, &result) | Run JavaScript and capture the return value |
chromedp.WaitVisible(sel) | Block until an element is visible |
chromedp.WaitReady(sel) | Block until an element is ready |
Remote Chrome connection
Connect to an already-running Chrome instance (useful in Docker or CI):
go
allocCtx, cancel := chromedp.NewRemoteAllocator(
context.Background(),
"ws://localhost:9222/json",
)
defer cancel()
ctx, cancel := chromedp.NewContext(allocCtx)
defer cancel()All 24 official examples
Clone and run any of the examples from the official repo:
bash
git clone https://github.com/chromedp/examples
cd examples/screenshot
go run main.goAvailable examples: click, cookie, download_file, download_image, emulate, eval, fast, forecast, geoip, headers, keys, latlon, logic, multi, pdf, proxy, remote, screenshot, submit, subtree, text, upload, visible.