launcher

package
v0.114.7 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2023 License: MIT Imports: 32 Imported by: 0

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)
// 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()

var cmd *exec.Cmd
if true { // decide whether to use leakless or not
	cmd = leakless.New().Command(path, args...)
} else {
	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)
// 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)
if path, exists := launcher.LookPath(); exists {
	u := launcher.New().Bin(path).MustLaunch()
	rod.New().ControlURL(u).MustConnect()
}
Output:

Index

Examples

Constants

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

RevisionDefault for chromium

View Source
const RevisionPlaywright = 1080

RevisionPlaywright for arm linux

Variables

View Source
var DefaultBrowserDir = filepath.Join(map[string]string{
	"windows": filepath.Join(os.Getenv("APPDATA")),
	"darwin":  filepath.Join(os.Getenv("HOME"), ".cache"),
	"linux":   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 DefaultUserDataDirPrefix = filepath.Join(os.TempDir(), "rod", "user-data")

DefaultUserDataDirPrefix ...

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

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

Functions

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 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 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"

Types

type Browser

type Browser struct {
	Context context.Context

	// Hosts are the candidates to download the browser.
	// Such as [HostGoogle] or [HostNPM].
	Hosts []Host

	// Revision of the browser to use
	Revision int

	// 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
}

Browser is a helper to download browser smartly

func NewBrowser

func NewBrowser() *Browser

NewBrowser with default values

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.

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 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.

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.

func NewAppMode

func NewAppMode(u string) *Launcher

NewAppMode is a preset to run the browser like a native application.

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) 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) 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) 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) 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) 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) Leakless

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

Leakless switch. If enabled, the browser will be force killed after the Go process exits. The doc of leakless: https://github.com/ysmood/leakless.

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) 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.

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 the browser to auto download

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) 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
Package main ...
Package main ...
chrome-exit-err
Package main ...
Package main ...
chrome-lib-missing
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