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()
}
Output:
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()
}
Output:
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()
}
}
Output:
Index ¶
- Constants
- Variables
- func CheckFileSHA256(path, sum string) error
- func HostGoogle(revision int) string
- func HostNPM(revision int) string
- func HostPlaywright(revision int) string
- func InstallLatestChromeForTesting(ctx context.Context, headlessShell bool) (bin string, removed int, err error)
- func LatestChromeForTesting(ctx context.Context, client *http.Client, channel string) (string, error)
- func LookPath() (found string, has bool)
- func MustResolveURL(u string) string
- func Open(url string)
- func PipeSupported() bool
- func PruneOlderBrowsers(root, keep string) (int, error)
- func ResolveURL(u string) (string, error)
- func SweepUserDataDirs(root string, minAge time.Duration) (removed int, err error)
- type Browser
- type Host
- type Launcher
- func (l *Launcher) AlwaysOpenPDFExternally() *Launcher
- func (l *Launcher) Append(name flags.Flag, values ...string) *Launcher
- func (l *Launcher) Bin(path string) *Launcher
- func (l *Launcher) Cleanup()
- func (l *Launcher) Client() (*cdp.Client, error)
- func (l *Launcher) ClientHeader() (string, http.Header)
- func (l *Launcher) Compliant(enable bool) *Launcher
- func (l *Launcher) Context(ctx context.Context) *Launcher
- func (l *Launcher) Delete(name flags.Flag) *Launcher
- func (l *Launcher) Devtools(autoOpenForTabs bool) *Launcher
- func (l *Launcher) DropPrivileges(uid, gid int) *Launcher
- func (l *Launcher) Env(env ...string) *Launcher
- func (l *Launcher) FormatArgs() []string
- func (l *Launcher) Get(name flags.Flag) string
- func (l *Launcher) GetFlags(name flags.Flag) ([]string, bool)
- func (l *Launcher) HardenedDefaults() *Launcher
- func (l *Launcher) Has(name flags.Flag) bool
- func (l *Launcher) Headless(enable bool) *Launcher
- func (l *Launcher) HeadlessNew(enable bool) *Launcher
- func (l *Launcher) HeadlessShell(enable bool) *Launcher
- func (l *Launcher) IgnoreCerts(pks []crypto.PublicKey) error
- func (l *Launcher) JSON() []byte
- func (l *Launcher) KeepUserDataDir() *Launcher
- func (l *Launcher) Kill()
- func (l *Launcher) Launch() (string, error)
- func (l *Launcher) LaunchPipe() (*cdp.Client, error)
- func (l *Launcher) LaunchTimeout(d time.Duration) *Launcher
- func (l *Launcher) Leakless(enable bool) *Launcher
- func (l *Launcher) Logger(w io.Writer) *Launcher
- func (l *Launcher) MustClient() *cdp.Client
- func (l *Launcher) MustLaunch() string
- func (l *Launcher) NoInheritEnv(enable bool) *Launcher
- func (l *Launcher) NoSandbox(enable bool) *Launcher
- func (l *Launcher) PID() int
- func (l *Launcher) Preferences(pref string) *Launcher
- func (l *Launcher) ProfileDir(dir string) *Launcher
- func (l *Launcher) Proxy(host string) *Launcher
- func (l *Launcher) RemoteDebuggingPort(port int) *Launcher
- func (l *Launcher) Revision(rev int) *Launcher
- func (l *Launcher) Set(name flags.Flag, values ...string) *Launcher
- func (l *Launcher) StartURL(u string) *Launcher
- func (l *Launcher) UserDataDir(dir string) *Launcher
- func (l *Launcher) WindowPosition(x, y int) *Launcher
- func (l *Launcher) WindowSize(x, y int) *Launcher
- func (l *Launcher) WorkingDir(path string) *Launcher
- func (l *Launcher) XVFB(args ...string) *Launcher
- type Manager
- type URLParser
Examples ¶
Constants ¶
const (
// HeaderName for remote launch.
HeaderName = "Rod-Launcher"
)
const RevisionDefault = 1321438
RevisionDefault for chromium.
const RevisionPlaywright = 1148
RevisionPlaywright for arm linux.
Variables ¶
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.
var ChromeForTestingVersionsURL = "https://googlechromelabs.github.io/chrome-for-testing/last-known-good-versions.json"
ChromeForTestingVersionsURL lists the latest Chrome for Testing version per channel.
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".
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.
var DefaultUserDataDirPrefix = filepath.Join(os.TempDir(), "rod", "user-data")
DefaultUserDataDirPrefix ...
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.
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.
var ErrAlreadyLaunched = errors.New("already launched")
ErrAlreadyLaunched is an error that indicates the launcher has already been launched.
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.
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.
var ErrUnsafeArchive = errors.New("archive entry escapes target directory")
ErrUnsafeArchive is returned when an archive entry would escape the target directory.
var LaunchOutputLimit = 64 << 10
LaunchOutputLimit is how much browser output is kept and attached to a launch error.
var MaxDownloadSize int64 = 2 << 30
MaxDownloadSize caps a browser archive and its extracted content.
Functions ¶
func CheckFileSHA256 ¶
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 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 ¶
LookPath searches for the browser executable from often used paths on current operating system.
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 ¶
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 ¶
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 ¶
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 ¶
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) Download ¶
Download browser from the fastest host. It will race downloading a TCP packet from each host and use the fastest host.
func (*Browser) Get ¶
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.
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 ¶
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 ¶
NewAppMode is a preset to run the browser like a native application. The u should be a URL.
func NewManaged ¶
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 ¶
AlwaysOpenPDFExternally switch. It will set chromium user preferences to enable the always_open_pdf_externally option.
func (*Launcher) Bin ¶
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) ClientHeader ¶
ClientHeader for launching browser remotely via the launcher.Manager.
func (*Launcher) Compliant ¶
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) DropPrivileges ¶
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 ¶
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 ¶
FormatArgs returns the formatted arg list for cli.
func (*Launcher) HardenedDefaults ¶
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) Headless ¶
Headless switch. Whether to run browser in headless mode. A mode without visible UI.
func (*Launcher) HeadlessNew ¶
HeadlessNew switch is the "--headless=new" switch: https://developer.chrome.com/docs/chromium/new-headless
func (*Launcher) HeadlessShell ¶
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 ¶
IgnoreCerts configure the Chrome's ignore-certificate-errors-spki-list argument with the public keys.
func (*Launcher) KeepUserDataDir ¶
KeepUserDataDir after remote browser is closed. By default launcher.FlagUserDataDir will be removed.
func (*Launcher) Launch ¶
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 ¶
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 ¶
LaunchTimeout bounds how long Launch waits for the browser to start. Zero uses DefaultLaunchTimeout, a negative value waits forever.
func (*Launcher) Leakless ¶
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 ¶
Logger to handle stdout and stderr from browser. For example, pipe all browser output to stdout:
launcher.New().Logger(os.Stdout)
func (*Launcher) MustClient ¶
MustClient similar to Launcher.Client.
func (*Launcher) MustLaunch ¶
MustLaunch is similar to Launch.
func (*Launcher) NoInheritEnv ¶
NoInheritEnv starts the browser with a minimal environment (PATH, HOME, TMPDIR) instead of the parent process environment.
func (*Launcher) NoSandbox ¶
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) Preferences ¶
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 ¶
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) RemoteDebuggingPort ¶
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 ¶
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 ¶
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) UserDataDir ¶
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 ¶
WindowPosition for the browser.
func (*Launcher) WindowSize ¶
WindowSize for the browser.
func (*Launcher) WorkingDir ¶
WorkingDir to launch the browser process.
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
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.
Source Files
¶
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 |