launcher

package
v0.104.1 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2022 License: MIT Imports: 26 Imported by: 280

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/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
	"github.com/go-rod/rod/lib/utils"
	"github.com/ysmood/leakless"
)

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

	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)
package main

import (
	"os"

	"github.com/go-rod/rod"
	"github.com/go-rod/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/go-rod/rod"
	"github.com/go-rod/rod/lib/launcher"
)

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

Index

Examples

Constants

View Source
const DefaultRevision = 983092

DefaultRevision for chrome

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

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

Functions

func HostGoogle

func HostGoogle(revision int) string

HostGoogle to download browser

func HostNPM added in v0.102.0

func HostNPM(revision int) string

HostNPM to download browser

func LookPath added in v0.91.0

func LookPath() (found string, has bool)

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

func MustResolveURL added in v0.65.0

func MustResolveURL(u string) string

MustResolveURL is similar to ResolveURL

func Open added in v0.91.0

func Open(url string)

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

func ResolveURL added in v0.65.0

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.
	Hosts []Host

	// Revision of the browser to use
	Revision int

	// Dir to download broweser.
	Dir string

	// Log to print output
	Logger io.Writer

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

Browser is a helper to download browser smartly

func NewBrowser

func NewBrowser() *Browser

NewBrowser with default values

func (*Browser) Destination added in v0.90.0

func (lc *Browser) Destination() string

Destination of the downloaded browser executable

func (*Browser) Download

func (lc *Browser) Download() (err error)

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

func (*Browser) Exists added in v0.91.0

func (lc *Browser) Exists() bool

Exists returns true if the browser executable path exists.

func (*Browser) Get

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

Get is a smart helper to get the browser executable path. If Destination doesn't exists it will download the browser to Destination.

func (*Browser) MustGet added in v0.90.0

func (lc *Browser) MustGet() string

MustGet is similar with Get

type Host added in v0.91.0

type Host func(revision int) string

Host to download 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 added in v0.98.0

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 NewManaged added in v0.98.0

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 added in v0.48.0

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 added in v0.49.7

func (l *Launcher) Cleanup()

Cleanup wait until the Browser exits and remove UserDataDir

func (*Launcher) Client

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

Client for launching browser remotely, such as browser from a docker container.

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 added in v0.56.0

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("TZ=America/New_York"). Timezone list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

func (*Launcher) FormatArgs

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

FormatArgs returns the formated 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 added in v0.98.0

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) 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 added in v0.59.0

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 UserDataDir to the same location.

func (*Launcher) Leakless added in v0.57.1

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 added in v0.56.0

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) MustLaunch added in v0.50.0

func (l *Launcher) MustLaunch() string

MustLaunch is similar to Launch

func (*Launcher) NoSandbox added in v0.94.3

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) ProfileDir added in v0.78.3

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 added in v0.57.2

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

Proxy switch. When disabled leakless will be disabled.

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 added in v0.103.0

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 to launch the browser.

func (*Launcher) StartURL added in v0.81.3

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 added in v0.56.0

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

WorkingDir to launch the browser process.

func (*Launcher) XVFB added in v0.86.1

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 added in v0.98.0

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 dynamicall 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 added in v0.98.0

func NewManager() *Manager

NewManager instance

func (*Manager) ServeHTTP added in v0.98.0

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

type URLParser added in v0.56.0

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 added in v0.56.0

func NewURLParser() *URLParser

NewURLParser instance

func (*URLParser) Context added in v0.101.0

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

Context sets the context

func (*URLParser) Err added in v0.89.2

func (r *URLParser) Err() error

Err returns the common error parsed from stdout and stderr

func (*URLParser) Write added in v0.56.0

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

Write interface

Directories

Path Synopsis
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