headless_browser

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2026 License: MIT Imports: 11 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

headless_browser

A simple headless browser library powered by go-rod, with built-in stealth mode support.

This is a hard fork of xpzouying/headless_browser (forked at v0.4.0). The module path is github.com/alex-soldatkin/headless_browser, so a consumer that already imports the upstream path only needs a replace directive and no source changes:

require github.com/xpzouying/headless_browser v0.4.0
replace github.com/xpzouying/headless_browser => github.com/alex-soldatkin/headless_browser v0.5.0

The upstream API is kept backward compatible.

Installation

go get github.com/alex-soldatkin/headless_browser

Usage

package main

import (
    "time"
    
    "github.com/alex-soldatkin/headless_browser"
)

func main() {
    // Create browser with default settings (headless mode)
    browser := headless_browser.New()
    defer browser.Close()
    
    // Create a new page
    page := browser.NewPage()
    defer page.Close()
    
    // Navigate to a website
    page.Timeout(30 * time.Second).
        MustNavigate("https://example.com").
        MustWaitStable()
}

Configuration Options

// Run in non-headless mode (visible browser)
browser := headless_browser.New(
    headless_browser.WithHeadless(false),
)

// Set custom user agent
browser := headless_browser.New(
    headless_browser.WithUserAgent("Custom User Agent"),
)

// Set cookies (JSON format)
browser := headless_browser.New(
    headless_browser.WithCookies(`[{"name":"session","value":"abc123","domain":"example.com"}]`),
)

// Combine multiple options
browser := headless_browser.New(
    headless_browser.WithHeadless(false),
    headless_browser.WithUserAgent("Custom User Agent"),
    headless_browser.WithCookies(cookiesJSON),
)

Fork additions

Persistent profiles: WithUserDataDir

Upstream's Close() calls launcher.Cleanup(), which does an unconditional os.RemoveAll of the user data directory — a persistent Chrome profile would be destroyed on every clean shutdown. (rod's rod-keep-user-data-dir flag does not help: it is only honoured by the remote launcher Manager.)

WithUserDataDir sets the flag and marks the directory as owned by the caller, so Close() leaves it alone while still waiting for the browser process to exit:

browser := headless_browser.New(
    headless_browser.WithUserDataDir("/var/lib/myapp/chrome-profile"),
)
defer browser.Close() // profile survives

Without the option, behaviour is unchanged: rod's temp profile is still removed.

Escape hatch: WithLauncherHook

Runs against the rod launcher after every other flag is applied and immediately before MustLaunch, so you can reach anything rod exposes without a bespoke option per need:

headless_browser.WithLauncherHook(func(l *launcher.Launcher) {
    l.Delete("enable-automation")
    l.Env("LANG=zh_CN.UTF-8")
    l.Preferences(`{"profile":{"exit_type":"Normal"}}`)
})
Per-page setup: WithPageHook

Runs on every page returned by NewPage, after the consistent UA override. An error is logged and does not abort page creation.

headless_browser.WithPageHook(func(p *rod.Page) error {
    return proto.EmulationSetDeviceMetricsOverride{
        Width: 1280, Height: 800, DeviceScaleFactor: 1,
    }.Call(p)
})

Multiple WithLauncherHook / WithPageHook options compose, in the order given.

Browser.Rod()

Returns the underlying *rod.Browser for browser-level CDP calls this package does not wrap.

Testing

The browser tests need a real Chrome/Chromium. They use launcher.LookPath() and are skipped when nothing is found; point them at a specific binary with:

HEADLESS_BROWSER_BIN=/path/to/Chromium go test ./...

Example

package main

import (
    "time"
    
    "github.com/alex-soldatkin/headless_browser"
)

func main() {
    // Create browser instance
    browser := headless_browser.New(headless_browser.WithHeadless(false))
    defer browser.Close()

    // Create new page with stealth mode
    page := browser.NewPage()
    defer page.Close()

    // Navigate and wait for page to be stable
    page.Timeout(30 * time.Second).
        MustNavigate("https://www.haha.ai").
        MustWaitStable()

    // Additional page operations can be performed here
    time.Sleep(1 * time.Second)
}

Documentation

Overview

Package headless_browser provides a simple headless browser library powered by go-rod with built-in stealth mode support.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Browser

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

Browser represents a headless browser instance with an underlying rod.Browser and launcher.

func New

func New(options ...Option) *Browser

New creates a new Browser instance with the provided options. It initializes a Chrome browser with stealth mode enabled.

func (*Browser) Close

func (b *Browser) Close()

Close closes the browser and cleans up resources.

launcher.Cleanup waits for the browser process to exit and then does an unconditional os.RemoveAll of the user data dir. When the caller supplied the directory (WithUserDataDir) we drop the flag from the launcher first, which makes Cleanup's RemoveAll a no-op (os.RemoveAll("") returns nil) while still waiting for the process to exit.

func (*Browser) NewPage

func (b *Browser) NewPage() *rod.Page

NewPage creates a new page. 若启用 StealthJS 则注入 go-rod/stealth 补丁;否则返回普通页面(交给源码级指纹补丁)。 若配置了一致 UA 覆盖,则在返回前套用,补回 UA 版本保真度。

func (*Browser) Rod

func (b *Browser) Rod() *rod.Browser

Rod returns the underlying rod.Browser, for browser-level CDP calls that this package does not wrap.

type Config

type Config struct {
	Headless      bool   // Whether to run browser in headless mode
	UserAgent     string // 自定义 UA。空 = 不覆盖,交给浏览器/指纹补丁自报(推荐,避免与 Client Hints 矛盾)
	Cookies       string // JSON string of cookies to set
	ChromeBinPath string // Custom Chrome/Chromium executable path
	Proxy         string // Proxy server URL (e.g. "http://host:port", "socks5://host:port")

	// Fingerprint 为 true 时,传入 CloakBrowser 的源码级指纹参数
	// (--fingerprint={seed} 与 --fingerprint-platform={platform}),激活其一致指纹引擎。
	// 仅对 CloakBrowser Chromium 有效;普通 Chrome 会忽略这些未知参数。
	Fingerprint         bool
	FingerprintPlatform string // 空 = 按运行 OS 自动:linux/windows→windows,darwin→macos
	FingerprintSeed     int    // 0 = 每次启动随机 seed

	// StealthJS 是否用 go-rod/stealth 注入 JS 指纹补丁。
	// 用 CloakBrowser 时应设为 false:源码级补丁已处理,再注入 JS 反而制造矛盾且本身可被检测。
	StealthJS bool

	// Language 覆盖 Accept-Language 与 navigator.languages(如 "zh-CN")。空 = 不覆盖。
	// 仅在启用 Fingerprint 的一致 UA 覆盖时生效。
	Language string

	// ExtraFlags 透传任意浏览器启动 flag(如 fingerprint-chromium 的
	// "fingerprint-brand":"Chrome"、"fingerprint-hardware-concurrency":"8")。
	// 键不带前导 "--"。
	ExtraFlags map[string]string

	// UserDataDir is the Chrome profile directory (--user-data-dir). When set,
	// the profile persists across runs and Close() will not delete it.
	// Empty = rod picks a temp directory and removes it on Close().
	UserDataDir string

	// LauncherHook runs against the launcher after every other flag has been
	// applied and before MustLaunch. Use it to Delete flags, set Env or
	// Preferences, or reach anything else rod's launcher exposes.
	LauncherHook func(*launcher.Launcher)

	// PageHook runs on every page returned by NewPage, after the UA override.
	PageHook func(*rod.Page) error

	Trace bool // Whether to enable tracing (not implemented yet)
}

Config holds the configuration options for the browser.

type Option

type Option func(*Config)

Option is a functional option for configuring the browser.

func WithChromeBinPath

func WithChromeBinPath(path string) Option

WithChromeBinPath sets a custom Chrome/Chromium executable path. If not set or empty, launcher will auto-detect or download a browser. Common paths:

  • macOS: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
  • Linux: "/usr/bin/google-chrome" or "/usr/bin/chromium"
  • Windows: "C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"

func WithCookies

func WithCookies(cookies string) Option

WithCookies sets cookies for the browser from a JSON string. The cookies should be in the format expected by proto.NetworkCookie.

func WithExtraFlags

func WithExtraFlags(flags map[string]string) Option

WithExtraFlags 透传任意浏览器启动 flag(键不带前导 "--")。

func WithFingerprint

func WithFingerprint(platform string) Option

WithFingerprint 启用 CloakBrowser 源码级指纹引擎。 platform 传空则按运行 OS 自动选择(Linux 服务器呈现 Windows 画像,mac 呈现 macOS)。

func WithFingerprintSeed

func WithFingerprintSeed(seed int) Option

WithFingerprintSeed 固定指纹 seed(0 表示每次随机)。同一 seed 产出同一套一致指纹。

func WithHeadless

func WithHeadless(headless bool) Option

WithHeadless sets whether the browser should run in headless mode.

func WithLanguage

func WithLanguage(lang string) Option

WithLanguage 覆盖 Accept-Language 与 navigator.languages(如 "zh-CN")。仅在启用 Fingerprint 时生效。

func WithLauncherHook

func WithLauncherHook(hook func(*launcher.Launcher)) Option

WithLauncherHook registers a callback invoked with the rod launcher after all other flags have been applied and immediately before MustLaunch.

This is the general escape hatch for anything this package does not wrap, for example:

WithLauncherHook(func(l *launcher.Launcher) {
	l.Delete("enable-automation")
	l.Env("LANG=zh_CN.UTF-8")
	l.Preferences(`{"profile":{"exit_type":"Normal"}}`)
})

Hooks are applied in the order the options were given.

func WithPageHook

func WithPageHook(hook func(*rod.Page) error) Option

WithPageHook registers a callback run on every page created by NewPage, after the consistent UA override (if any) has been applied. Use it for per-page CDP setup, such as proto.EmulationSetDeviceMetricsOverride for window geometry.

An error returned by the hook is logged and does not abort page creation. Hooks are applied in the order the options were given.

func WithProxy

func WithProxy(proxy string) Option

WithProxy sets a proxy server for all browser requests. Supports HTTP, HTTPS, and SOCKS5 proxies. Example: "http://proxy.example.com:8080", "socks5://127.0.0.1:1080"

Note: Chrome's --proxy-server flag does not support embedded credentials (e.g. "http://user:pass@host:port"). For authenticated proxies, handle authentication separately at the page level.

func WithStealthJS

func WithStealthJS(enabled bool) Option

WithStealthJS 控制是否注入 go-rod/stealth 的 JS 补丁。用 CloakBrowser 时应传 false。

func WithTrace

func WithTrace() Option

func WithUserAgent

func WithUserAgent(userAgent string) Option

WithUserAgent sets a custom user agent string for the browser. 注意:配合 CloakBrowser 使用时不建议设置,强制 UA 会与 Client Hints 产生矛盾。

func WithUserDataDir

func WithUserDataDir(dir string) Option

WithUserDataDir sets an explicit Chrome profile directory (--user-data-dir).

Besides passing the flag to the launcher, it marks the directory as owned by the caller: Close() then skips launcher.Cleanup()'s unconditional os.RemoveAll of the user data dir, so cookies, local storage and the rest of the profile survive a clean shutdown.

Note that rod's flags.KeepUserDataDir ("rod-keep-user-data-dir") does not help here: it is only honoured by the remote launcher Manager, never by the local Cleanup path.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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