launcher

package
v0.117.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 34 Imported by: 1 module, 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

Overview

A lib helps to find, launch or download the browser. You can also use it as a standalone lib without Rod.

Documentation

Overview

Package launcher for launching browser utils.

Example (Custom_launch)
package main

import (
	"os/exec"

	"github.com/projectdiscovery/rod"
	"github.com/projectdiscovery/rod/lib/launcher"
	"github.com/projectdiscovery/rod/lib/utils"
)

func main() {
	// get the browser executable path
	path := launcher.NewBrowser().MustGet()

	// use the FormatArgs to construct args, this line is optional, you can construct the args manually
	args := launcher.New().FormatArgs()

	cmd := exec.Command(path, args...)

	parser := launcher.NewURLParser()
	cmd.Stderr = parser
	utils.E(cmd.Start())
	u := launcher.MustResolveURL(<-parser.URL)

	rod.New().ControlURL(u).MustConnect()
}
Example (Print_browser_CLI_output)
package main

import (
	"os"

	"github.com/projectdiscovery/rod"
	"github.com/projectdiscovery/rod/lib/launcher"
)

func main() {
	// Pipe the browser stderr and stdout to os.Stdout .
	u := launcher.New().Logger(os.Stdout).MustLaunch()
	rod.New().ControlURL(u).MustConnect()
}
Example (Use_system_browser)
package main

import (
	"github.com/projectdiscovery/rod"
	"github.com/projectdiscovery/rod/lib/launcher"
)

func main() {
	if path, exists := launcher.LookPath(); exists {
		u := launcher.New().Bin(path).MustLaunch()
		rod.New().ControlURL(u).MustConnect()
	}
}

Index

Examples

Constants

View Source
const (
	// HeaderName for remote launch.
	HeaderName = "Rod-Launcher"
)
View Source
const RevisionDefault = 1321438

RevisionDefault for chromium.

View Source
const RevisionPlaywright = 1148

RevisionPlaywright for arm linux.

Variables

View Source
var ChromeForTestingPins = map[string]string{}

ChromeForTestingPins maps "product/platform/version" to the SHA-256 hex digest of that archive. product is productChrome or "chrome-headless-shell", platform is linux64, linux-arm64, mac-arm64, mac-x64, win64 or win32. A listed version is refused when the download does not match. Chrome for Testing does not publish these hashes, so latest stable is not listed: the hash of the first completed download is stored beside the cache and required for every later download of that same version.

View Source
var ChromeForTestingVersionsURL = "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json"

ChromeForTestingVersionsURL lists the latest Chrome for Testing version per channel.

View Source
var DefaultBrowserDir = filepath.Join(map[string]string{
	goosWindows: os.Getenv("APPDATA"),
	goosDarwin:  filepath.Join(os.Getenv("HOME"), ".cache"),
	goosLinux:   filepath.Join(os.Getenv("HOME"), ".cache"),
}[runtime.GOOS], "rod", "browser")

DefaultBrowserDir for downloaded browser. For unix is "$HOME/.cache/rod/browser", for Windows it's "%APPDATA%\rod\browser".

View Source
var DefaultLaunchTimeout = 60 * time.Second

DefaultLaunchTimeout bounds how long Launch waits for the browser to print its DevTools address when Launcher.LaunchTimeout is not set.

View Source
var DefaultUserDataDirPrefix = filepath.Join(os.TempDir(), "rod", "user-data")

DefaultUserDataDirPrefix ...

View Source
var DownloadHeaderTimeout = 60 * time.Second

DownloadHeaderTimeout bounds the wait for a download host to answer with response headers when Browser.HTTPClient is not set. It includes the connect and TLS steps. Without it a host that accepts the connection and sends nothing blocks the launch forever, and Get never reaches the cached browser. It does not bound the body. DownloadIdleTimeout covers the body, so a large download still works. A caller that sets its own client keeps its own timeouts. Zero or less turns the bound off.

View Source
var DownloadIdleTimeout = 60 * time.Second

DownloadIdleTimeout aborts a browser download that receives no bytes for this long. Without it a stalled CDN connection blocks the launch forever.

View Source
var ErrAlreadyLaunched = errors.New("already launched")

ErrAlreadyLaunched is an error that indicates the launcher has already been launched.

View Source
var ErrLaunchTimeout = errors.New("launcher: browser did not start in time")

ErrLaunchTimeout is returned when the browser does not report its DevTools address in time.

View Source
var ErrMuslNoBrowser = errors.New("launcher: downloadable browsers need glibc and this host uses musl, " +
	"install Chromium (apk add chromium) or set Launcher.Bin")

ErrMuslNoBrowser is returned by Browser.Get on a musl host, such as Alpine, when no browser is installed. Chrome for Testing and the Chromium snapshots are glibc builds and cannot run there.

View Source
var ErrUnsafeArchive = errors.New("archive entry escapes target directory")

ErrUnsafeArchive is returned when an archive entry would escape the target directory.

View Source
var LaunchOutputLimit = 64 << 10

LaunchOutputLimit is how much browser output is kept and attached to a launch error.

View Source
var MaxDownloadSize int64 = 2 << 30

MaxDownloadSize caps a browser archive and its extracted content.

Functions

func CheckFileSHA256

func CheckFileSHA256(path, sum string) error

CheckFileSHA256 reports whether path hashes to sum. sum is hex, with or without surrounding whitespace. Use this for a browser archive you downloaded yourself. The built-in downloader does not see the archive bytes, so it cannot apply the pin itself.

func HostGoogle

func HostGoogle(revision int) string

HostGoogle to download browser.

func HostNPM

func HostNPM(revision int) string

HostNPM to download browser.

func HostPlaywright

func HostPlaywright(revision int) string

HostPlaywright to download browser.

func InstallLatestChromeForTesting

func InstallLatestChromeForTesting(ctx context.Context, headlessShell bool) (bin string, removed int, err error)

InstallLatestChromeForTesting downloads the current Stable Chrome for Testing build and removes older cached builds of the same product. With headlessShell the smaller chrome-headless-shell build is used. The returned path is the browser executable.

func LatestChromeForTesting

func LatestChromeForTesting(ctx context.Context, client *http.Client, channel string) (string, error)

LatestChromeForTesting returns the current version of a Chrome for Testing channel: "Stable", "Beta", "Dev", or "Canary".

func LookPath

func LookPath() (found string, has bool)

LookPath searches for the browser executable from often used paths on current operating system.

func MustResolveURL

func MustResolveURL(u string) string

MustResolveURL is similar to ResolveURL.

func Open

func Open(url string)

Open tries to open the url via system's default browser.

func PipeSupported

func PipeSupported() bool

PipeSupported reports whether LaunchPipe can run on this platform. Go does not pass ExtraFiles to child processes on Windows, so there the browser has to be launched on a debugging port instead.

func PruneOlderBrowsers

func PruneOlderBrowsers(root, keep string) (int, error)

PruneOlderBrowsers removes cached browser directories under root that are the same product as keep and an older version. keep is the directory of the version to retain. A directory whose version is not older, or whose name is not a downloaded browser, is left in place. The SHA-256 pin beside a removed directory is removed with it.

func ResolveURL

func ResolveURL(u string) (string, error)

ResolveURL by requesting the u, it will try best to normalize the u. The format of u can be "9222", ":9222", "host:9222", "ws://host:9222", "wss://host:9222", "https://host:9222" "http://host:9222". The return string will look like: "ws://host:9222/devtools/browser/4371405f-84df-4ad6-9e0f-eab81f7521cc"

func SweepUserDataDirs

func SweepUserDataDirs(root string, minAge time.Duration) (removed int, err error)

SweepUserDataDirs removes browser profile directories under root that no running browser owns, such as the ones left behind when this process was killed before Launcher.Cleanup ran. A directory is kept while its SingletonLock or the launcher's own lock names a live process, or while it is younger than minAge so a browser that is still starting is not swept. An empty root means DefaultUserDataDirPrefix.

Types

type Browser

type Browser struct {
	Context context.Context

	// Hosts are the candidates to download the browser.
	// Such as [HostGoogle] or [HostNPM]. When nil, the default hosts for the
	// selected browser are used. An empty non-nil list downloads nothing.
	Hosts []Host

	// Revision of a Chromium snapshot to download, such as [RevisionDefault].
	// When zero, the latest stable Chrome for Testing build is downloaded.
	Revision int

	// HeadlessShell downloads chrome-headless-shell instead of full Chrome.
	// The shell cannot show a window, so [Browser.Headful] wins. Only applies
	// when Revision is zero and the browser was not created by
	// [NewChromeForTesting].
	HeadlessShell bool

	// Headful downloads the full Chrome build, because chrome-headless-shell
	// cannot show a window. Only applies when Revision is zero and the browser
	// was not created by [NewChromeForTesting].
	Headful bool

	// RootDir to download different browser versions.
	RootDir string

	// Log to print output
	Logger utils.Logger

	// LockPort a tcp port to prevent race downloading. Default is 2968 .
	LockPort int

	// HTTPClient to download the browser
	HTTPClient *http.Client

	// SHA256 of the downloaded archive. When set, a mismatching download is
	// rejected before extraction.
	SHA256 string
	// contains filtered or unexported fields
}

Browser is a helper to download browser smartly.

By default it downloads the latest stable full Chrome from Chrome for Testing. Set HeadlessShell for the smaller chrome-headless-shell build, or Revision for a Chromium snapshot.

func NewBrowser

func NewBrowser() *Browser

NewBrowser with default values. The default is the latest stable full Chrome from Chrome for Testing.

func NewChromeForTesting

func NewChromeForTesting(version string, headlessShell bool) *Browser

NewChromeForTesting returns a Browser that downloads the given Chrome for Testing version. With headlessShell the smaller chrome-headless-shell build is used, which only runs headless and starts faster.

func (*Browser) BinPath

func (lc *Browser) BinPath() string

BinPath to download the browser executable.

func (*Browser) Dir

func (lc *Browser) Dir() string

Dir to download the browser.

func (*Browser) Download

func (lc *Browser) Download() error

Download browser from the fastest host. It will race downloading a TCP packet from each host and use the fastest host.

func (*Browser) Get

func (lc *Browser) Get() (string, error)

Get is a smart helper to get the browser executable path. If Browser.BinPath is not valid it will auto download the browser to Browser.BinPath. On a musl host it returns the browser found by LookPath instead, or ErrMuslNoBrowser.

func (*Browser) MustGet

func (lc *Browser) MustGet() string

MustGet is similar with Get.

func (*Browser) Validate

func (lc *Browser) Validate() error

Validate returns nil if the browser executable is valid. If the executable is malformed it will return error.

type Host

type Host func(revision int) string

Host formats a revision number to a downloadable URL for the browser.

func HostChromeForTesting

func HostChromeForTesting(version string, headlessShell bool) Host

HostChromeForTesting returns the download URL of a Chrome for Testing build. The revision argument of Host is ignored.

type Launcher

type Launcher struct {
	Flags map[flags.Flag][]string `json:"flags"`
	// contains filtered or unexported fields
}

Launcher is a helper to launch browser binary smartly.

func MustNewManaged

func MustNewManaged(serviceURL string) *Launcher

MustNewManaged is similar to NewManaged.

func New

func New() *Launcher

New returns the default arguments to start browser. Headless will be enabled by default. Leakless will be enabled by default. UserDataDir will use OS tmp dir by default, this folder will usually be cleaned up by the OS after reboot. It will auto download the latest stable full Chrome for the current platform. Launcher.HeadlessShell selects the smaller chrome-headless-shell build. Check Launcher.Bin and Launcher.Revision for more info.

func NewAppMode

func NewAppMode(u string) *Launcher

NewAppMode is a preset to run the browser like a native application. The u should be a URL.

func NewManaged

func NewManaged(serviceURL string) (*Launcher, error)

NewManaged creates a default Launcher instance from launcher.Manager. The serviceURL must point to a launcher.Manager. It will send a http request to the serviceURL to get the default settings of the Launcher instance. For example if the launcher.Manager running on a Linux machine will return different default settings from the one on Mac. If Launcher.Leakless is enabled, the remote browser will be killed after the websocket is closed.

func NewUserMode

func NewUserMode() *Launcher

NewUserMode is a preset to enable reusing current user data. Useful for automation of personal browser. If you see any error, it may because you can't launch debug port for existing browser, the solution is to completely close the running browser. Unfortunately, there's no API for rod to tell it automatically yet.

func (*Launcher) AlwaysOpenPDFExternally

func (l *Launcher) AlwaysOpenPDFExternally() *Launcher

AlwaysOpenPDFExternally switch. It will set chromium user preferences to enable the always_open_pdf_externally option.

func (*Launcher) Append

func (l *Launcher) Append(name flags.Flag, values ...string) *Launcher

Append values to the flag.

func (*Launcher) Bin

func (l *Launcher) Bin(path string) *Launcher

Bin of the browser binary path to launch, if the path is not empty the auto download will be disabled.

func (*Launcher) Cleanup

func (l *Launcher) Cleanup()

Cleanup wait until the Browser exits and remove flags.UserDataDir.

func (*Launcher) Client

func (l *Launcher) Client() (*cdp.Client, error)

Client for launching browser remotely via the launcher.Manager.

func (*Launcher) ClientHeader

func (l *Launcher) ClientHeader() (string, http.Header)

ClientHeader for launching browser remotely via the launcher.Manager.

func (*Launcher) Compliant

func (l *Launcher) Compliant(enable bool) *Launcher

Compliant controls how the browser is launched. It is on by default: full Chrome starts without the automation switch, so navigator.webdriver is false, and [Browser.Compliant] aligns the user agent and client hints with that browser. A headless shell is not used. Pass false to opt out and keep the automation switch and the launcher's headless-shell setting.

func (*Launcher) Context

func (l *Launcher) Context(ctx context.Context) *Launcher

Context sets the context.

func (*Launcher) Delete

func (l *Launcher) Delete(name flags.Flag) *Launcher

Delete a flag.

func (*Launcher) Devtools

func (l *Launcher) Devtools(autoOpenForTabs bool) *Launcher

Devtools switch to auto open devtools for each tab.

func (*Launcher) DropPrivileges

func (l *Launcher) DropPrivileges(uid, gid int) *Launcher

DropPrivileges runs the browser as uid and gid. On Unix the profile directory is created and given to that user before start. The call does nothing until it is used. It is not supported on Windows.

func (*Launcher) Env

func (l *Launcher) Env(env ...string) *Launcher

Env to launch the browser process. The default value is os.Environ(). Usually you use it to set the timezone env. Such as:

Env(append(os.Environ(), "TZ=Asia/Tokyo")...)

func (*Launcher) FormatArgs

func (l *Launcher) FormatArgs() []string

FormatArgs returns the formatted arg list for cli.

func (*Launcher) Get

func (l *Launcher) Get(name flags.Flag) string

Get flag's first value.

func (*Launcher) GetFlags

func (l *Launcher) GetFlags(name flags.Flag) ([]string, bool)

GetFlags from settings.

func (*Launcher) HardenedDefaults

func (l *Launcher) HardenedDefaults() *Launcher

HardenedDefaults applies the shared headless flag preset. It does not change --no-sandbox, and it does not set --disable-web-security. disable-ipc-flooding-protection is removed because it makes some Chrome builds loop.

func (*Launcher) Has

func (l *Launcher) Has(name flags.Flag) bool

Has flag or not.

func (*Launcher) Headless

func (l *Launcher) Headless(enable bool) *Launcher

Headless switch. Whether to run browser in headless mode. A mode without visible UI.

func (*Launcher) HeadlessNew

func (l *Launcher) HeadlessNew(enable bool) *Launcher

HeadlessNew switch is the "--headless=new" switch: https://developer.chrome.com/docs/chromium/new-headless

func (*Launcher) HeadlessShell

func (l *Launcher) HeadlessShell(enable bool) *Launcher

HeadlessShell downloads chrome-headless-shell instead of full Chrome. The shell is smaller. It cannot show a window, so a headful launch ignores this and downloads full Chrome. It also has no window.chrome, no plugins and no PDF viewer, and its client hints say HeadlessChrome.

func (*Launcher) IgnoreCerts

func (l *Launcher) IgnoreCerts(pks []crypto.PublicKey) error

IgnoreCerts configure the Chrome's ignore-certificate-errors-spki-list argument with the public keys.

func (*Launcher) JSON

func (l *Launcher) JSON() []byte

JSON serialization.

func (*Launcher) KeepUserDataDir

func (l *Launcher) KeepUserDataDir() *Launcher

KeepUserDataDir after remote browser is closed. By default launcher.FlagUserDataDir will be removed.

func (*Launcher) Kill

func (l *Launcher) Kill()

Kill the browser process.

func (*Launcher) Launch

func (l *Launcher) Launch() (string, error)

Launch a standalone temp browser instance and returns the debug url. bin and profileDir are optional, set them to empty to use the default values. If you want to reuse sessions, such as cookies, set the Launcher.UserDataDir to the same location.

Please note launcher can only be used once.

func (*Launcher) LaunchPipe

func (l *Launcher) LaunchPipe() (*cdp.Client, error)

LaunchPipe starts the browser with --remote-debugging-pipe and returns a CDP client on that pipe. No debugging port is opened. Closing the client closes the pipe, which makes Chrome exit.

func (*Launcher) LaunchTimeout

func (l *Launcher) LaunchTimeout(d time.Duration) *Launcher

LaunchTimeout bounds how long Launch waits for the browser to start. Zero uses DefaultLaunchTimeout, a negative value waits forever.

func (*Launcher) Leakless

func (l *Launcher) Leakless(enable bool) *Launcher

Leakless is kept so existing callers compile. The helper binary is not used. The browser is started in its own process group and is killed when this process dies: by Pdeathsig on Linux, a job object on Windows, and a /bin/sh watchdog elsewhere.

func (*Launcher) Logger

func (l *Launcher) Logger(w io.Writer) *Launcher

Logger to handle stdout and stderr from browser. For example, pipe all browser output to stdout:

launcher.New().Logger(os.Stdout)

func (*Launcher) MustClient

func (l *Launcher) MustClient() *cdp.Client

MustClient similar to Launcher.Client.

func (*Launcher) MustLaunch

func (l *Launcher) MustLaunch() string

MustLaunch is similar to Launch.

func (*Launcher) NoInheritEnv

func (l *Launcher) NoInheritEnv(enable bool) *Launcher

NoInheritEnv starts the browser with a minimal environment (PATH, HOME, TMPDIR) instead of the parent process environment.

func (*Launcher) NoSandbox

func (l *Launcher) NoSandbox(enable bool) *Launcher

NoSandbox switch. Whether to run browser in no-sandbox mode. Linux users may face "running as root without --no-sandbox is not supported" in some Linux/Chrome combinations. This function helps switch mode easily. Be aware disabling sandbox is not trivial. Use at your own risk. Related doc: https://bugs.chromium.org/p/chromium/issues/detail?id=638180

func (*Launcher) PID

func (l *Launcher) PID() int

PID returns the browser process pid.

func (*Launcher) Preferences

func (l *Launcher) Preferences(pref string) *Launcher

Preferences set chromium user preferences, such as set the default search engine or disable the pdf viewer. The pref is a json string, the doc is here https://src.chromium.org/viewvc/chrome/trunk/src/chrome/common/pref_names.cc

func (*Launcher) ProfileDir

func (l *Launcher) ProfileDir(dir string) *Launcher

ProfileDir is the browser profile the browser will use. When set to empty, the profile 'Default' is used. Related article: https://superuser.com/a/377195

func (*Launcher) Proxy

func (l *Launcher) Proxy(host string) *Launcher

Proxy for the browser.

func (*Launcher) RemoteDebuggingPort

func (l *Launcher) RemoteDebuggingPort(port int) *Launcher

RemoteDebuggingPort to launch the browser. Zero for a random port. Zero is the default value. If it's not zero and the Launcher.Leakless is disabled, the launcher will try to reconnect to it first, if the reconnection fails it will launch a new browser.

func (*Launcher) Revision

func (l *Launcher) Revision(rev int) *Launcher

Revision of a Chromium snapshot to auto download, such as RevisionDefault. Without it the launcher downloads the latest stable full Chrome. Launcher.HeadlessShell selects chrome-headless-shell instead.

func (*Launcher) Set

func (l *Launcher) Set(name flags.Flag, values ...string) *Launcher

Set a command line argument when launching the browser. Be careful the first argument is a flag name, it shouldn't contain values. The values the will be joined with comma. A flag can have multiple values. If no values are provided the flag will be a boolean flag. You can use the Launcher.FormatArgs to debug the final CLI arguments. List of available flags: https://peter.sh/experiments/chromium-command-line-switches

func (*Launcher) StartURL

func (l *Launcher) StartURL(u string) *Launcher

StartURL to launch.

func (*Launcher) UserDataDir

func (l *Launcher) UserDataDir(dir string) *Launcher

UserDataDir is where the browser will look for all of its state, such as cookie and cache. When set to empty, browser will use current OS home dir. Related doc: https://chromium.googlesource.com/chromium/src/+/master/docs/user_data_dir.md

func (*Launcher) WindowPosition

func (l *Launcher) WindowPosition(x, y int) *Launcher

WindowPosition for the browser.

func (*Launcher) WindowSize

func (l *Launcher) WindowSize(x, y int) *Launcher

WindowSize for the browser.

func (*Launcher) WorkingDir

func (l *Launcher) WorkingDir(path string) *Launcher

WorkingDir to launch the browser process.

func (*Launcher) XVFB

func (l *Launcher) XVFB(args ...string) *Launcher

XVFB enables to run browser in by XVFB. Useful when you want to run headful mode on linux.

type Manager

type Manager struct {
	// Logger for key events
	Logger utils.Logger

	// Defaults should return the default Launcher settings
	Defaults func(http.ResponseWriter, *http.Request) *Launcher

	// BeforeLaunch hook is called right before the launching with the Launcher instance that will be used
	// to launch the browser.
	// Such as use it to filter malicious values of Launcher.UserDataDir, Launcher.Bin, or Launcher.WorkingDir.
	BeforeLaunch func(*Launcher, http.ResponseWriter, *http.Request)
}

Manager is used to launch browsers via http server on another machine. The reason why we have Manager is after we launcher a browser, we can't dynamically change its CLI arguments, such as "--headless". The Manager allows us to decide what CLI arguments to pass to the browser when launch it remotely. The work flow looks like:

|      Machine X       |                             Machine Y                                    |
| NewManaged("a.com") -|-> http.ListenAndServe("a.com", launcher.NewManager()) --> launch browser |

1. X send a http request to Y, Y respond default Launcher settings based the OS of Y.
2. X start a websocket connect to Y with the Launcher settings
3. Y launches a browser with the Launcher settings X
4. Y transparently proxy the websocket connect between X and the launched browser

func NewManager

func NewManager() *Manager

NewManager instance.

func (*Manager) ServeHTTP

func (m *Manager) ServeHTTP(w http.ResponseWriter, r *http.Request)

type URLParser

type URLParser struct {
	URL    chan string
	Buffer string // buffer for the browser stdout
	// contains filtered or unexported fields
}

URLParser to get control url from stderr.

func NewURLParser

func NewURLParser() *URLParser

NewURLParser instance.

func (*URLParser) Context

func (r *URLParser) Context(ctx context.Context) *URLParser

Context sets the context.

func (*URLParser) Err

func (r *URLParser) Err() error

Err returns the common error parsed from stdout and stderr.

func (*URLParser) Write

func (r *URLParser) Write(p []byte) (n int, err error)

Write interface.

Directories

Path Synopsis
fixtures
chrome-empty command
Package main ...
Package main ...
chrome-exit-err command
Package main ...
Package main ...
chrome-lib-missing command
Package main ...
Package main ...
Package flags ...
Package flags ...
Package main ...
Package main ...
A server to help launch browser remotely
A server to help launch browser remotely

Jump to

Keyboard shortcuts

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