browsershot

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2026 License: MIT Imports: 17 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Convert a webpage to an image or PDF using headless Chrome

Latest version Tests Go Reference

Browsershot converts URLs and HTML to PNG, JPEG, WebP, PDF or rendered HTML. Puppeteer controls headless Chrome behind the scenes. This is the Go port of spatie/browsershot.

Support us

Support Spatie's open source work

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

Requires Go 1.27+, Node 22.12+, Puppeteer 23+ and Chrome.

go get github.com/spatie/browsershot-go@v0.1.0
npm install puppeteer

See requirements for custom Node, module and Chrome paths. No PHP runtime is needed.

Usage

import (
    "context"
    "github.com/spatie/browsershot-go"
)

err := browsershot.URL("https://example.com").
    WindowSize(1440, 900).
    FullPage().
    Save(context.Background(), "example.png")
if err != nil {
    return err
}

Use HTML("<h1>Hello world</h1>").Format("A4").SavePDF(ctx, "example.pdf") for a PDF. Screenshot(ctx) and PDF(ctx) return bytes. Evaluate(ctx, expression, &value) decodes a JavaScript result into a Go value.

Builders are mutable and not safe for concurrent use. Each output method opens a fresh page. Configure separate instances for concurrent work. Rendering accepts a context and waits use time.Duration. SetOption exposes Puppeteer options, WithRunner replaces browser execution, and TransformImage accepts custom image processing without a required image library.

Only render trusted URLs and HTML. Local files are blocked for supplied HTML unless you call AllowLocalFileAccess(). This does not make Chrome a sandbox for untrusted input or prevent access to internal HTTP services.

See the documentation.

Testing

go test -race ./...
BROWSERSHOT_INTEGRATION=1 go test -race -count=1 ./...

The integration suite launches Chrome. CI runs it on Linux, macOS and Windows. See testing.

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details. Coding agents should read AGENTS.md and load the relevant skills in .agents/skills/.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

Documentation

Overview

Package browsershot converts web pages and HTML to images, PDFs and HTML using Puppeteer.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidInput         = errors.New("invalid browser input")
	ErrElementNotFound      = errors.New("element not found")
	ErrUnsuccessfulResponse = errors.New("unsuccessful HTTP response")
	ErrRemoteConnection     = errors.New("remote browser connection failed")
)

Functions

This section is empty.

Types

type BrowserError

type BrowserError struct {
	Kind     error
	ExitCode int
	Message  string
}

BrowserError preserves the process exit code, diagnostics and a matchable error kind.

func (*BrowserError) Error

func (e *BrowserError) Error() string

func (*BrowserError) Unwrap

func (e *BrowserError) Unwrap() error

type Browsershot

type Browsershot struct {
	// contains filtered or unexported fields
}

Browsershot is a mutable page builder. Use separate instances in concurrent goroutines. The zero value is usable after SetURL, SetHTML or SetHTMLFromFilePath.

func HTML

func HTML(value string) *Browsershot

func HTMLFromFilePath

func HTMLFromFilePath(path string) *Browsershot

func New

func New() *Browsershot

func URL

func URL(value string) *Browsershot

func (*Browsershot) AddChromiumArguments

func (b *Browsershot) AddChromiumArguments(args ...string) *Browsershot

func (*Browsershot) AddScriptTag

func (b *Browsershot) AddScriptTag(options map[string]string) *Browsershot

func (*Browsershot) AddStyleTag

func (b *Browsershot) AddStyleTag(options map[string]string) *Browsershot

func (*Browsershot) AllowLocalFileAccess

func (b *Browsershot) AllowLocalFileAccess(enabled ...bool) *Browsershot

func (*Browsershot) Authenticate

func (b *Browsershot) Authenticate(username, password string) *Browsershot

func (*Browsershot) Base64PDF

func (b *Browsershot) Base64PDF(ctx context.Context) (string, error)

func (*Browsershot) Base64Screenshot

func (b *Browsershot) Base64Screenshot(ctx context.Context) (string, error)

func (*Browsershot) BlockDomains

func (b *Browsershot) BlockDomains(domains []string) *Browsershot

func (*Browsershot) BlockURLs

func (b *Browsershot) BlockURLs(urls []string) *Browsershot

func (*Browsershot) BodyHTML

func (b *Browsershot) BodyHTML(ctx context.Context) (string, error)

func (*Browsershot) Click

func (b *Browsershot) Click(selector string, options ...ClickOptions) *Browsershot

func (*Browsershot) Clip

func (b *Browsershot) Clip(x, y, width, height int) *Browsershot

func (*Browsershot) ConsoleMessages

func (b *Browsershot) ConsoleMessages(ctx context.Context) ([]ConsoleMessage, error)

func (*Browsershot) Delay

func (b *Browsershot) Delay(delay time.Duration) *Browsershot

func (*Browsershot) Device

func (b *Browsershot) Device(device string) *Browsershot

Device applies Puppeteer's device viewport. Call WindowSize afterward to override it.

func (*Browsershot) DeviceScaleFactor

func (b *Browsershot) DeviceScaleFactor(scale int) *Browsershot

func (*Browsershot) DisableCaptureURLs

func (b *Browsershot) DisableCaptureURLs() *Browsershot

func (*Browsershot) DisableImages

func (b *Browsershot) DisableImages() *Browsershot

func (*Browsershot) DisableJavascript

func (b *Browsershot) DisableJavascript() *Browsershot

func (*Browsershot) DisableRedirects

func (b *Browsershot) DisableRedirects() *Browsershot

func (*Browsershot) DismissDialogs

func (b *Browsershot) DismissDialogs() *Browsershot

func (*Browsershot) EmulateMedia

func (b *Browsershot) EmulateMedia(media string) *Browsershot

func (*Browsershot) EmulateMediaFeatures

func (b *Browsershot) EmulateMediaFeatures(features []map[string]string) *Browsershot

func (*Browsershot) Evaluate

func (b *Browsershot) Evaluate(ctx context.Context, expression string, target any) error

Evaluate decodes a JavaScript expression's JSON result into target, as json.Unmarshal does.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"

	"github.com/spatie/browsershot-go"
)

func main() {
	page := browsershot.HTML("<h1>Hello world</h1>")
	// A replacement runner can delegate execution to another service.
	page.WithRunner(func(ctx context.Context, command browsershot.Command) (browsershot.Result, error) {
		return browsershot.Result{Value: json.RawMessage(`{"title":"Hello world","count":7}`)}, nil
	})
	var result struct {
		Title string
		Count int
	}
	if err := page.Evaluate(context.Background(), `({title: document.title, count: 7})`, &result); err != nil {
		panic(err)
	}
	fmt.Println(result.Title, result.Count)
}
Output:
Hello world 7

func (*Browsershot) EvaluateOnNewDocument

func (b *Browsershot) EvaluateOnNewDocument(script string) *Browsershot

func (*Browsershot) FailedRequests

func (b *Browsershot) FailedRequests(ctx context.Context) ([]FailedRequest, error)

func (*Browsershot) FooterHTML

func (b *Browsershot) FooterHTML(value string) *Browsershot

func (*Browsershot) Format

func (b *Browsershot) Format(format string) *Browsershot

func (*Browsershot) FullPage

func (b *Browsershot) FullPage() *Browsershot

func (*Browsershot) HeaderHTML

func (b *Browsershot) HeaderHTML(value string) *Browsershot

func (*Browsershot) HideBackground

func (b *Browsershot) HideBackground() *Browsershot

func (*Browsershot) HideBrowserHeaderAndFooter

func (b *Browsershot) HideBrowserHeaderAndFooter() *Browsershot

func (*Browsershot) HideFooter

func (b *Browsershot) HideFooter() *Browsershot

func (*Browsershot) HideHeader

func (b *Browsershot) HideHeader() *Browsershot

func (*Browsershot) IgnoreHTTPSErrors

func (b *Browsershot) IgnoreHTTPSErrors() *Browsershot

func (*Browsershot) InitialPageNumber

func (b *Browsershot) InitialPageNumber(page int) *Browsershot

func (*Browsershot) Landscape

func (b *Browsershot) Landscape(enabled ...bool) *Browsershot

func (*Browsershot) LocatorClick

func (b *Browsershot) LocatorClick(selector string, options ...ClickOptions) *Browsershot

func (*Browsershot) Margins

func (b *Browsershot) Margins(top, right, bottom, left float64, unit ...string) *Browsershot

func (*Browsershot) Mobile

func (b *Browsershot) Mobile(enabled ...bool) *Browsershot

func (*Browsershot) NewHeadless

func (b *Browsershot) NewHeadless() *Browsershot

func (*Browsershot) NoSandbox

func (b *Browsershot) NoSandbox() *Browsershot

func (*Browsershot) Output

func (b *Browsershot) Output() *Result

Output returns diagnostics from the last execution. Configuration changes do not discard them.

func (*Browsershot) PDF

func (b *Browsershot) PDF(ctx context.Context) ([]byte, error)

func (*Browsershot) PageErrors

func (b *Browsershot) PageErrors(ctx context.Context) ([]PageError, error)

func (*Browsershot) Pages

func (b *Browsershot) Pages(ranges string) *Browsershot

func (*Browsershot) PaperSize

func (b *Browsershot) PaperSize(width, height float64, unit ...string) *Browsershot

func (*Browsershot) Post

func (b *Browsershot) Post(fields map[string]string) *Browsershot

func (*Browsershot) PreventUnsuccessfulResponse

func (b *Browsershot) PreventUnsuccessfulResponse(enabled ...bool) *Browsershot

func (*Browsershot) ProtocolTimeout

func (b *Browsershot) ProtocolTimeout(timeout time.Duration) *Browsershot

func (*Browsershot) RedirectHistory

func (b *Browsershot) RedirectHistory(ctx context.Context) ([]Response, error)

func (*Browsershot) Save

func (b *Browsershot) Save(ctx context.Context, path string) error

Save selects PDF for .pdf paths. Image format otherwise follows SetScreenshotType, not the extension.

func (*Browsershot) SavePDF

func (b *Browsershot) SavePDF(ctx context.Context, path string) error

func (*Browsershot) Scale

func (b *Browsershot) Scale(scale float64) *Browsershot

func (*Browsershot) Screenshot

func (b *Browsershot) Screenshot(ctx context.Context) ([]byte, error)

func (*Browsershot) Select

func (b *Browsershot) Select(selector string, index ...int) *Browsershot

func (*Browsershot) SelectOption

func (b *Browsershot) SelectOption(selector, value string) *Browsershot

func (*Browsershot) SelectorIndex

func (b *Browsershot) SelectorIndex(index int) *Browsershot

func (*Browsershot) SetBinPath

func (b *Browsershot) SetBinPath(path string) *Browsershot

func (*Browsershot) SetChromePath

func (b *Browsershot) SetChromePath(path string) *Browsershot

func (*Browsershot) SetContentURL

func (b *Browsershot) SetContentURL(value string) *Browsershot

func (*Browsershot) SetCustomTempPath

func (b *Browsershot) SetCustomTempPath(path string) *Browsershot

func (*Browsershot) SetEnvironmentOptions

func (b *Browsershot) SetEnvironmentOptions(env map[string]string) *Browsershot

func (*Browsershot) SetExtraHTTPHeaders

func (b *Browsershot) SetExtraHTTPHeaders(headers map[string]string) *Browsershot

func (*Browsershot) SetExtraNavigationHTTPHeaders

func (b *Browsershot) SetExtraNavigationHTTPHeaders(headers map[string]string) *Browsershot

func (*Browsershot) SetHTML

func (b *Browsershot) SetHTML(value string) *Browsershot

func (*Browsershot) SetHTMLFromFilePath

func (b *Browsershot) SetHTMLFromFilePath(path string) *Browsershot

func (*Browsershot) SetIncludePath

func (b *Browsershot) SetIncludePath(path string) *Browsershot

func (*Browsershot) SetNodeBinary

func (b *Browsershot) SetNodeBinary(path string) *Browsershot

func (*Browsershot) SetNodeEnv

func (b *Browsershot) SetNodeEnv(env map[string]string) *Browsershot

func (*Browsershot) SetNodeModulePath

func (b *Browsershot) SetNodeModulePath(path string) *Browsershot

func (*Browsershot) SetNpmBinary

func (b *Browsershot) SetNpmBinary(path string) *Browsershot

func (*Browsershot) SetOption

func (b *Browsershot) SetOption(key string, value any) *Browsershot

SetOption sets a Puppeteer option. Dotted keys address nested objects. Values must be JSON serializable. Validation and encoding errors surface when rendering.

func (*Browsershot) SetProxyServer

func (b *Browsershot) SetProxyServer(proxy string) *Browsershot

func (*Browsershot) SetRemoteInstance

func (b *Browsershot) SetRemoteInstance(host string, port int) *Browsershot

func (*Browsershot) SetScreenshotType

func (b *Browsershot) SetScreenshotType(format string, quality ...int) *Browsershot

func (*Browsershot) SetURL

func (b *Browsershot) SetURL(value string) *Browsershot

func (*Browsershot) SetWSEndpoint

func (b *Browsershot) SetWSEndpoint(endpoint string) *Browsershot

func (*Browsershot) ShowBackground

func (b *Browsershot) ShowBackground() *Browsershot

func (*Browsershot) ShowBrowserHeaderAndFooter

func (b *Browsershot) ShowBrowserHeaderAndFooter() *Browsershot

func (*Browsershot) TaggedPDF

func (b *Browsershot) TaggedPDF() *Browsershot

func (*Browsershot) ThrowOnRemoteConnectionError

func (b *Browsershot) ThrowOnRemoteConnectionError(enabled ...bool) *Browsershot

func (*Browsershot) Timeout

func (b *Browsershot) Timeout(timeout time.Duration) *Browsershot

func (*Browsershot) Touch

func (b *Browsershot) Touch(enabled ...bool) *Browsershot

func (*Browsershot) TransformImage

func (b *Browsershot) TransformImage(transform ImageTransform) *Browsershot

func (*Browsershot) TransparentBackground

func (b *Browsershot) TransparentBackground() *Browsershot

func (*Browsershot) TriggeredRequests

func (b *Browsershot) TriggeredRequests(ctx context.Context) ([]Request, error)

func (*Browsershot) Type

func (b *Browsershot) Type(selector, text string, delay ...time.Duration) *Browsershot

func (*Browsershot) UseCookies

func (b *Browsershot) UseCookies(cookies map[string]string, domain ...string) *Browsershot

func (*Browsershot) UsePipe

func (b *Browsershot) UsePipe() *Browsershot

func (*Browsershot) UserAgent

func (b *Browsershot) UserAgent(agent string) *Browsershot

func (*Browsershot) UserDataDir

func (b *Browsershot) UserDataDir(path string) *Browsershot

func (*Browsershot) WaitForFunction

func (b *Browsershot) WaitForFunction(expression string) *Browsershot

WaitForFunction uses animation-frame polling by default. Set functionPolling to "mutation" or a millisecond interval through SetOption to use another Puppeteer polling mode.

func (*Browsershot) WaitForSelector

func (b *Browsershot) WaitForSelector(selector string, options ...map[string]any) *Browsershot

func (*Browsershot) WaitUntilNetworkIdle

func (b *Browsershot) WaitUntilNetworkIdle(strict ...bool) *Browsershot

func (*Browsershot) WindowSize

func (b *Browsershot) WindowSize(width, height int) *Browsershot

func (*Browsershot) WithRunner

func (b *Browsershot) WithRunner(runner Runner) *Browsershot

func (*Browsershot) WriteOptionsToFile

func (b *Browsershot) WriteOptionsToFile() *Browsershot

type ClickOptions

type ClickOptions struct {
	Button string        `json:"button"`
	Count  int           `json:"clickCount"`
	Delay  time.Duration `json:"-"`
}

type Command

type Command struct {
	URL        string            `json:"url"`
	Action     string            `json:"action"`
	Options    map[string]any    `json:"options"`
	PostParams map[string]string `json:"postParams,omitempty"`
}

Command is the browser runner protocol. Options use Puppeteer's names.

type ConsoleMessage

type ConsoleMessage struct {
	Type       string          `json:"type"`
	Message    string          `json:"message"`
	Location   json.RawMessage `json:"location"`
	StackTrace json.RawMessage `json:"stackTrace"`
}

type FailedRequest

type FailedRequest struct {
	URL    string `json:"url"`
	Status int    `json:"status"`
}

type ImageTransform

type ImageTransform func(context.Context, []byte) ([]byte, error)

ImageTransform runs after screenshot capture, for in-memory and saved images alike. It receives and returns encoded image bytes in the selected screenshot format.

type PageError

type PageError struct {
	Name    string `json:"name"`
	Message string `json:"message"`
}

type Request

type Request struct {
	URL string `json:"url"`
}

type Response

type Response struct {
	URL     string            `json:"url"`
	Status  int               `json:"status"`
	Reason  string            `json:"reason"`
	Headers map[string]string `json:"headers"`
}

type Result

type Result struct {
	Value           json.RawMessage  `json:"result"`
	Exception       string           `json:"exception"`
	Requests        []Request        `json:"requestsList"`
	ConsoleMessages []ConsoleMessage `json:"consoleMessages"`
	FailedRequests  []FailedRequest  `json:"failedRequests"`
	RedirectHistory []Response       `json:"redirectHistory"`
	PageErrors      []PageError      `json:"pageErrors"`
}

Result contains the output and diagnostics of one browser operation, including failed operations.

type Runner

type Runner func(context.Context, Command) (Result, error)

Runner replaces browser execution, for example with a container or a hosted service. The command's temporary HTML URL remains valid until Runner returns.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL