User Agents

Web browsers and everyday web tech, explained

Screenshot HTML Pages with Go and Headless Chrome in Docker

· 5 min read · Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Capturing a visual snapshot of an HTML page using Go and Headless Chrome within a Docker container allows you to automate visual regression testing, generate PDF-like previews, or archive web content in a consistent environment. This process involves using the Chrome DevTools Protocol (CDP) via a Go library to control a browser instance that runs without a graphical user interface (GUI), all packaged inside a Linux container to ensure that dependencies like Chromium and its necessary shared libraries are present regardless of the host OS.

What You'll Need

  • Go (Golang) installed on your development machine (1.18 or later recommended).
  • Docker installed and running.
  • A basic understanding of the Chrome DevTools Protocol (CDP).
  • The chromedp library, which is the most popular Go package for driving headless Chrome.
  • A text editor or IDE.

Step-by-Step

  1. Initialize Your Go Module: Start by creating a new directory for your project and initializing the module. Run go mod init screenshot-app in your terminal. This creates a go.mod file to manage your dependencies.
  2. Install the chromedp Library: Run go get github.com/chromedp/chromedp. This library provides a high-level API to interact with Chrome, allowing you to navigate to URLs, wait for elements to load, and trigger the screenshot command without writing raw JSON-RPC calls to the browser.
  3. Write the Go Capture Logic: Create a file named main.go. You need to set up a context for chromedp. Because you are running in Docker, you must configure the browser options to include --no-sandbox and --disable-setuid-sandbox. Without these flags, Chrome will fail to launch inside a container due to Linux security restrictions on user namespaces.
  4. Implement the Screenshot Function: Inside your main.go, use chromedp.Run to execute a sequence of tasks. First, use chromedp.Navigate(url) to load the page. Second, use chromedp.FullScreenshot(&buf, 100) to capture the entire page height, or chromedp.Screenshot for the current viewport. Store the resulting byte slice in a buffer.
  5. Save the Output to a File: Use the os.WriteFile function to save the buffer to a .png file. Ensure the file path is within a directory that will be mapped to a Docker volume if you want to access the image on your host machine.
  6. Create the Dockerfile: This is the most critical step. You cannot use a standard golang:alpine image alone because it lacks the Chromium binary and the necessary system libraries (like nss, freetype, and libx11). Use a multi-stage build. In the first stage, compile your Go binary. In the second stage, use a Debian-based image (like debian:bookworm-slim) and install chromium via apt-get.
  7. Configure the Docker Environment: In your Dockerfile, ensure you set the environment variable CHROME_BIN to the path where Chromium is installed (usually /usr/bin/chromium). This allows chromedp to find the executable automatically.
  8. Build the Container: Run docker build -t go-screenshot .. This will compile your code and package it with the browser.
  9. Run the Container with Volume Mapping: To get the image out of the container, run docker run -v $(pwd)/output:/app/output go-screenshot. This maps your local output folder to the container's output directory.

Common Mistakes

One of the most frequent errors is forgetting the --no-sandbox flag. By default, Chrome uses a sandbox to isolate the browser process from the rest of the system. However, Docker containers run as root by default or lack the specific kernel capabilities required to create these namespaces. If you omit this flag, the Go program will hang or return a "browser failed to start" error.

Another common mistake is failing to wait for the page to fully render. Modern websites use JavaScript to load content asynchronously. If you trigger a screenshot immediately after chromedp.Navigate, you will often capture a blank page or a loading spinner. You should use chromedp.WaitVisible on a specific element that indicates the page is ready before taking the shot.

Developers also often use Alpine Linux to keep images small. While possible, installing Chromium on Alpine requires managing musl vs glibc compatibility issues and a long list of manual package dependencies. Using a slim Debian image is generally more stable for browser automation.

Tips

To capture a "Full Page" screenshot, you must first calculate the total height of the body element. Use chromedp.Evaluate to run a JavaScript snippet like document.body.scrollHeight, then use chromedp.EmulateViewport to resize the browser window to that exact height before capturing. This prevents the image from being cut off at the fold.

For better performance, reuse the browser instance. Starting a new Chrome process for every single screenshot is resource-heavy and slow. Create a single chromedp context and spawn new tabs (targets) for different URLs. This significantly reduces the overhead per image.

If you are capturing pages that require authentication, use chromedp.SetCookies to inject session cookies into the browser before navigating to the target URL. This avoids the need to automate complex login forms for every request.

Troubleshooting

If the container crashes with a "shared library missing" error (e.g., libnss3.so not found), it means your Docker image is missing a dependency. The best fix is to install the chromium package via the official package manager rather than downloading a standalone binary, as the package manager automatically resolves all shared library dependencies.

If the screenshot is blurry or has the wrong resolution, check your EmulateViewport settings. High-DPI screens can cause scaling issues. Explicitly setting the DeviceScaleFactor to 1 in the browser options ensures a consistent 1:1 pixel ratio regardless of the environment.

When the Go program hangs indefinitely, it is usually because chromedp.WaitVisible is looking for an element that never appears (perhaps due to a 404 error or a JavaScript crash). Always wrap your wait functions in a context.WithTimeout to ensure the program exits if the page fails to load within a reasonable timeframe (e.g., 30 seconds).

Frequently Asked Questions

Can I use this to capture password-protected pages?

Yes, provided you can obtain the session cookies or automate the login process using chromedp.SendKeys and chromedp.Click before triggering the screenshot.

Does this work for Single Page Applications (SPAs) like React or Vue?

Yes, because Headless Chrome executes JavaScript. As long as you use WaitVisible to ensure the JS has finished rendering the DOM, the screenshot will be accurate.

How do I handle different screen sizes for mobile testing?

You can use chromedp.EmulateViewport to set the width and height to match common mobile devices (e.g., 375x812 for iPhone X) before capturing the image.

Is there a way to make the Docker image smaller?

Use a multi-stage build to ensure the Go compiler and build tools are not included in the final image. Stick to debian-slim and only install the chromium package and ca-certificates.

Can I capture a specific element instead of the whole page?

Yes, you can use chromedp.Screenshot by passing a selector to target a specific DOM element rather than the entire viewport.