Skip to content

chrome.New

Michael Kenney edited this page Sep 29, 2018 · 4 revisions

Local Chromium

Initialize and start a Chrome process in headless mode to interact with. See https://developers.google.com/web/updates/2017/04/headless-chrome#cli for details about startup flags:

package main

import (
	chrome "github.com/mkenney/go-chrome/tot"
)

func main() {

	// Define a chrome instance with remote debugging enabled.
	browser := chrome.New(
		// See https://developers.google.com/web/updates/2017/04/headless-chrome#cli
		// for details about startup flags
		&chrome.Flags{
			"addr":               "0.0.0.0",
			"disable-extensions": nil,
			"disable-gpu":        nil,
			"headless":           nil,
			"hide-scrollbars":    nil,
			"no-first-run":       nil,
			"no-sandbox":         nil,
			"port":               9222,
			"remote-debugging-address": "0.0.0.0",
			"remote-debugging-port":    9222,
		},
		"/usr/bin/google-chrome", // Path to Chromium binary
		"/tmp",      // Set the Chromium working directory
		"/dev/null", // Ignore internal Chromium output, set to empty string for os.Stdout
		"/dev/null", // Ignore internal Chromium errors, set to empty string for os.Stderr
	)

	// Start the chrome process.
	if err := browser.Launch(); nil != err {
		panic(err.Error())
	}

	// Open a tab and navigate to a web page.
	tab, err := browser.NewTab("https://www.google.com")
	if nil != err {
		panic(err.Error())
	}
}

Remote Chromium

It is also possible to initialize a Chrome struct for a remote Chromium instance by omitting the Launch call. Most of the other flags can be omitted in this case:

package main

import (
	chrome "github.com/mkenney/go-chrome/tot"
)

func main() {

	// Define a chrome instance with remote debugging enabled.
	browser := chrome.New(
		// Initialize a Chrome instance with information about how to
		// contact the remote Chromium process.
		&chrome.Flags{
			"addr":               "0.0.0.0",
			"port":               9222,
			"remote-debugging-address": "0.0.0.0",
			"remote-debugging-port":    9222,
		},
		"", "", "", "",
	)

	// Open a tab in the remote Chromium instance and navigate to a web page.
	tab, err := browser.NewTab("https://www.google.com")
	if nil != err {
		panic(err.Error())
	}
}

The above example will work with the provided docker-compose.yml file which will launch a local Headless Chrome instance for development.