Examples

Screenshot of a particular area with Go and Puppeteer

Heads up before you start

Puppeteer has no Go port. The closest equivalent is chromedp — an actively maintained Go library that drives Chrome over the same DevTools Protocol Puppeteer uses. These examples use chromedp.

Install chromedp

go get github.com/chromedp/chromedp

chromedp drives a Chrome or Chromium you already have installed — it does not download its own browser, and finds the system Chrome automatically. Run the command inside a Go module (go mod init myproject first if you need one). Some examples also import github.com/chromedp/cdproto for DevTools commands — run go mod tidy after adding the code to pull it in.

Take a screenshot of the clip and save to file

package main

import (
	"context"
	"log"
	"os"

	"github.com/chromedp/cdproto/page"
	"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://www.htmltoimage.com/demo"),
		chromedp.ActionFunc(func(ctx context.Context) error {
			var err error
			buf, err = page.CaptureScreenshot().
				WithClip(&page.Viewport{X: 0, Y: 0, Width: 480, Height: 240, Scale: 1}).
				Do(ctx)
			return err
		}),
	); err != nil {
		log.Fatal(err)
	}
	if err := os.WriteFile("clip.png", buf, 0o644); err != nil {
		log.Fatal(err)
	}
}

Find out how to take a full-page screenshot with Go and Puppeteer.

That was 32 lines of code — plus a browser to run in production

Keeping headless browsers fed, patched and scaled is a job in itself. We built Urlbox so the same screenshot is one API call:

curl "https://api.urlbox.com/v1/YOUR_API_KEY/png?url=https://example.com"

Try the Urlbox screenshot API — free trial, no browser babysitting.