Categorygithub.com/LightningDev1/chromiumdp
modulepackage
0.0.0-20231128154929-66ef7c9d7fb7
Repository: https://github.com/lightningdev1/chromiumdp.git
Documentation: pkg.go.dev

# README

About chromedp

Package chromedp is a faster, simpler way to drive browsers supporting the Chrome DevTools Protocol in Go without external dependencies.

Unit Tests Go Reference Releases

Installing

Install in the usual Go way:

$ go get -u github.com/chromedp/chromedp

Examples

Refer to the Go reference for the documentation and examples. Additionally, the examples repository contains more examples on complex actions, and other common high-level tasks such as taking full page screenshots.

Frequently Asked Questions

I can't see any Chrome browser window

By default, Chrome is run in headless mode. See DefaultExecAllocatorOptions, and an example to override the default options.

I'm seeing "context canceled" errors

When the connection to the browser is lost, chromedp cancels the context, and it may result in this error. This occurs, for example, if the browser is closed manually, or if the browser process has been killed or otherwise terminated.

Chrome exits as soon as my Go program finishes

On Linux, chromedp is configured to avoid leaking resources by force-killing any started Chrome child processes. If you need to launch a long-running Chrome instance, manually start Chrome and connect using RemoteAllocator.

Executing an action without Run results in "invalid context"

By default, a chromedp context does not have an executor, however one can be specified manually if necessary; see issue #326 for an example.

I can't use an Action with Run because it returns many values

Wrap it with an ActionFunc:

ctx, cancel := chromedp.NewContext(context.Background())
defer cancel()
chromedp.Run(ctx, chromedp.ActionFunc(func(ctx context.Context) error {
	_, err := domain.SomeAction().Do(ctx)
	return err
}))

I want to use chromedp on a headless environment

The simplest way is to run the Go program that uses chromedp inside the chromedp/headless-shell image. That image contains headless-shell, a smaller headless build of Chrome, which chromedp is able to find out of the box.

Resources

# Packages

Package device contains device emulation definitions for use with chromedp's Emulate action.
Package kb provides keyboard mappings for Chrome DOM Keys for use with input events.

# Functions

After is an element query option that sets a func to execute after the matched nodes have been returned by the browser, and after the node condition is true.
AtLeast is an element query option to set a minimum number of elements that must be returned by the query.
Attributes is an element query action that retrieves the element attributes for the first element node matching the selector.
AttributesAll is an element query action that retrieves the element attributes for all element nodes matching the selector.
AttributeValue is an element query action that retrieves the element attribute value for the first element node matching the selector.
Blur is an element query action that unfocuses (blurs) the first element node matching the selector.
Button is a mouse action option to set the button to click from a string.
ButtonLeft is a mouse action option to set the button clicked as the left mouse button.
ButtonMiddle is a mouse action option to set the button clicked as the middle mouse button.
ButtonModifiers is a mouse action option to add additional input modifiers for a button click.
ButtonNone is a mouse action option to set the button clicked as none (used for mouse movements).
ButtonRight is a mouse action option to set the button clicked as the right mouse button.
ButtonType is a mouse action option to set the button to click.
ByFunc is an element query action option to set the func used to select elements.
ByID is an element query option to select a single element by its CSS #id.
ByJSPath is an element query option to select elements by the "JS Path" value (as shown in the Chrome DevTools UI).
ByNodeID is an element query option to select elements by their node IDs.
ByQuery is an element query action option to select a single element by the DOM.querySelector command.
ByQueryAll is an element query action option to select elements by the DOM.querySelectorAll command.
BySearch is an element query option to select elements by the DOM.performSearch command.
CallFunctionOn is an action to call a JavaScript function, unmarshaling the result of the function to res.
Cancel cancels a chromedp context, waits for its resources to be cleaned up, and returns any error encountered during that process.
CaptureScreenshot is an action that captures/takes a screenshot of the current browser viewport.
Clear is an element query action that clears the values of any input/textarea element nodes matching the selector.
Click is an element query action that sends a mouse click event to the first element node matching the selector.
ClickCount is a mouse action option to set the click count.
CombinedOutput is used to set an io.Writer where stdout and stderr from the browser will be sent.
ComputedStyle is an element query action that retrieves the computed style of the first element node matching the selector.
DialContext dials the specified websocket URL using gobwas/ws.
Dimensions is an element query action that retrieves the box model dimensions for the first element node matching the selector.
DisableGPU is the command line option to disable the GPU process.
DoubleClick is an element query action that sends a mouse double click event to the first element node matching the selector.
Emulate is an action to emulate a specific device.
EmulateLandscape is an emulate viewport option to set the device viewport screen orientation in landscape primary mode and an angle of 90.
EmulateMobile is an emulate viewport option to toggle the device viewport to display as a mobile device.
EmulateOrientation is an emulate viewport option to set the device viewport screen orientation.
EmulatePortrait is an emulate viewport option to set the device viewport screen orientation in portrait primary mode and an angle of 0.
EmulateReset is an action to reset the device emulation.
EmulateScale is an emulate viewport option to set the device viewport scaling factor.
EmulateTouch is an emulate viewport option to enable touch emulation.
EmulateViewport is an action to change the browser viewport.
Env is a list of generic environment variables in the form NAME=value to pass into the new Chrome process.
EvalAsValue is an evaluate option that will cause the evaluated JavaScript expression to encode the result of the expression as a JSON-encoded value.
EvalIgnoreExceptions is an evaluate option that will cause JavaScript evaluation to ignore exceptions.
EvalObjectGroup is an evaluate option to set the object group.
Evaluate is an action to evaluate the JavaScript expression, unmarshaling the result of the script evaluation to res.
EvaluateAsDevTools is an action that evaluates a JavaScript expression as Chrome DevTools would, evaluating the expression in the "console" context, and making the Command Line API available to the script.
EvalWithCommandLineAPI is an evaluate option to make the DevTools Command Line API available to the evaluated script.
ExecPath returns an ExecAllocatorOption which uses the given path to execute browser processes.
Flag is a generic command line option to pass a flag to Chrome.
Focus is an element query action that focuses the first element node matching the selector.
FromContext extracts the Context data stored inside a context.Context.
FromNode is an element query action option where a query will be run.
FullScreenshot takes a full screenshot with the specified image quality of the entire browser viewport.
Headless is the command line option to run in headless mode.
IgnoreCertErrors is the command line option to ignore certificate-related errors.
InnerHTML is an element query action that retrieves the inner html of the first element node matching the selector.
JavascriptAttribute is an element query action that retrieves the JavaScript attribute for the first element node matching the selector.
KeyEvent is a key action that synthesizes a keyDown, char, and keyUp event for each rune contained in keys along with any supplied key options.
KeyEventNode is a key action that dispatches a key event on an element node.
KeyModifiers is a key action option to add additional modifiers on the key press.
ListenBrowser adds a function which will be called whenever a browser event is received on the chromedp context.
ListenTarget adds a function which will be called whenever a target event is received on the chromedp context.
Location is an action that retrieves the document location.
MatchedStyle is an element query action that retrieves the matched style information for the first element node matching the selector.
ModifyCmdFunc allows for running an arbitrary function on the browser exec.Cmd object.
MouseClickNode is an action that dispatches a mouse left button click event at the center of a specified node.
MouseClickXY is an action that sends a left mouse button click (i.e., mousePressed and mouseReleased event) to the X, Y location.
MouseEvent is a mouse event action to dispatch the specified mouse event type at coordinates x, y.
Navigate is an action that navigates the current frame.
NavigateBack is an action that navigates the current frame backwards in its history.
NavigateForward is an action that navigates the current frame forwards in its history.
NavigateToHistoryEntry is an action to navigate to the specified navigation entry.
NavigationEntries is an action that retrieves the page's navigation history entries.
NewBrowser creates a new browser.
NewContext creates a chromedp context from the parent context.
NewExecAllocator creates a new context set up with an ExecAllocator, suitable for use with NewContext.
NewRemoteAllocator creates a new context set up with a RemoteAllocator, suitable for use with NewContext.
NodeEnabled is an element query option to wait until all queried element nodes have been sent by the browser and are enabled (i.e., do not have a 'disabled' attribute).
NoDefaultBrowserCheck is the Chrome command line option to disable the default browser check.
NodeIDs is an element query action that retrieves the element node IDs matching the selector.
NodeNotPresent is an element query option to wait until no elements are present that match the query.
NodeNotVisible is an element query option to wait until all queried element nodes have been sent by the browser and are not visible.
NodeReady is an element query option to wait until all queried element nodes have been sent by the browser.
Nodes is an element query action that retrieves the document element nodes matching the selector.
NodeSelected is an element query option to wait until all queried element nodes have been sent by the browser and are selected (i.e., has 'selected' attribute).
NodeVisible is an element query option to wait until all queried element nodes have been sent by the browser and are visible.
NoFirstRun is the Chrome command line option to disable the first run dialog.
NoModifyURL is a RemoteAllocatorOption that prevents the remote allocator from modifying the websocket debugger URL passed to it.
NoSandbox is the Chrome command line option to disable the sandbox.
OuterHTML is an element query action that retrieves the outer html of the first element node matching the selector.
Poll is a poll action that will wait for a general JavaScript predicate.
PollFunction is a poll action that will wait for a general JavaScript predicate.
ProxyServer is the command line option to set the outbound proxy server.
Query is a query action that queries the browser for specific element node(s) matching the criteria.
QueryAfter is an element query action that queries the browser for selector sel.
Reload is an action that reloads the current page.
RemoveAttribute is an element query action that removes the element attribute with name from the first element node matching the selector.
Reset is an element query action that resets the parent form of the first element node matching the selector.
ResetViewport is an action to reset the browser viewport to the default values the browser was started with.
RetryInterval is an element query action option to set the retry interval to specify how often it should retry when it failed to select the target element(s).
Run runs an action against context.
RunResponse is an alternative to Run which can be used with a list of actions that trigger a page navigation, such as clicking on a link or button.
Screenshot is an element query action that takes a screenshot of the first element node matching the selector.
ScreenshotScale is like [Screenshot] but accepts a scale parameter that specifies the page scale factor.
ScrollIntoView is an element query action that scrolls the window to the first element node matching the selector.
SendKeys is an element query action that synthesizes the key up, char, and down events as needed for the runes in v, sending them to the first element node matching the selector.
SetAttributes is an element query action that sets the element attributes for the first element node matching the selector.
SetAttributeValue is an element query action that sets the element attribute with name to value for the first element node matching the selector.
SetJavascriptAttribute is an element query action that sets the JavaScript attribute for the first element node matching the selector.
SetUploadFiles is an element query action that sets the files to upload (i.e., for a input[type="file"] node) for the first element node matching the selector.
SetValue is an element query action that sets the JavaScript value of the first element node matching the selector.
Sleep is an empty action that calls time.Sleep with the specified duration.
Stop is an action that stops all navigation and pending resource retrieval.
Submit is an element query action that submits the parent form of the first element node matching the selector.
Targets lists all the targets in the browser attached to the given context.
Text is an element query action that retrieves the visible text of the first element node matching the selector.
TextContent is an element query action that retrieves the text content of the first element node matching the selector.
Title is an action that retrieves the document title.
UserAgent is the command line option to set the default User-Agent header.
UserDataDir is the command line option to set the user data dir.
Value is an element query action that retrieves the JavaScript value field of the first element node matching the selector.
WaitEnabled is an element query action that waits until the element matching the selector is enabled (i.e., does not have attribute 'disabled').
WaitFunc is an element query option to set a custom node condition wait.
WaitNewTarget can be used to wait for the current target to open a new target.
WaitNotPresent is an element query action that waits until no elements are present matching the selector.
WaitNotVisible is an element query action that waits until the element matching the selector is not visible.
WaitReady is an element query action that waits until the element matching the selector is ready (i.e., has been "loaded").
WaitSelected is an element query action that waits until the element matching the selector is selected (i.e., has attribute 'selected').
WaitVisible is an element query action that waits until the element matching the selector is visible.
WindowSize is the command line option to set the initial window size.
WithBrowserDebugf is a browser option to specify a func to log actual websocket messages.
WithBrowserErrorf is a browser option to specify a func to receive error logging.
WithBrowserLogf is a browser option to specify a func to receive general logging.
WithBrowserOption allows passing a number of browser options to the allocator when allocating a new browser.
WithConnDebugf is a dial option to set a protocol logger.
WithConsolef is a browser option to specify a func to receive chrome log events.
WithDebugf is a shortcut for WithBrowserOption(WithBrowserDebugf(f)).
WithDialTimeout is a browser option to specify the timeout when dialing a browser's websocket address.
WithErrorf is a shortcut for WithBrowserOption(WithBrowserErrorf(f)).
WithExistingBrowserContext sets up a context to create a new target in the specified browser context.
WithLogf is a shortcut for WithBrowserOption(WithBrowserLogf(f)).
WithNewBrowserContext sets up a context to create a new BrowserContext, and create a new target in this BrowserContext.
WithPollingArgs provides extra arguments to pass to the predicate.
WithPollingInFrame specifies the frame in which to evaluate the predicate.
WithPollingInterval makes it to poll the predicate with the specified interval.
WithPollingMutation makes it to poll the predicate on every DOM mutation.
WithPollingTimeout specifies the maximum time to wait for the predicate returns truthy value.
WithTargetID sets up a context to be attached to an existing target, instead of creating a new one.
WSURLReadTimeout sets the waiting time for reading the WebSocket URL.

# Constants

ErrChannelClosed is the channel closed error.
ErrDisabled is the disabled error.
ErrHasResults is the has results error.
ErrInvalidBoxModel is the invalid box model error.
ErrInvalidContext is the invalid context error.
ErrInvalidDimensions is the invalid dimensions error.
ErrInvalidTarget is the invalid target error.
ErrInvalidWebsocketMessage is the invalid websocket message.
ErrJSNull is the error that the value of RemoteObject is null.
ErrJSUndefined is the error that the type of RemoteObject is "undefined".
ErrNoResults is the no results error.
ErrNotSelected is the not selected error.
ErrNotVisible is the not visible error.
ErrPollingTimeout is the error that the timeout reached before the pageFunction returns a truthy value.
ErrVisible is the visible error.

# Variables

DefaultExecAllocatorOptions are the ExecAllocator options used by NewContext if the given parent context doesn't have an allocator set up.

# Structs

Browser is the high-level Chrome DevTools Protocol browser manager, handling the browser process runner, WebSocket clients, associated targets, and network, page, and DOM events.
Conn implements Transport with a gobwas/ws websocket connection.
Context is attached to any context.Context which is valid for use with Run.
ExecAllocator is an Allocator which starts new browser processes on the host machine.
RemoteAllocator is an Allocator which connects to an already running Chrome process via a websocket URL.
Selector holds information pertaining to an element selection query.
Target manages a Chrome DevTools Protocol target.

# Interfaces

Action is the common interface for an action that will be executed against a context and frame handler.
An Allocator is responsible for creating and managing a number of browsers.
Device is the shared interface for known device types.
Transport is the common interface to send/receive messages to a target.

# Type aliases

ActionFunc is an adapter to allow the use of ordinary func's as an Action.
BrowserOption is a browser option.
CallAction are actions that calls a JavaScript function using runtime.CallFunctionOn.
CallOption is a function to modify the runtime.CallFunctionOnParams to provide more information.
ContextOption is a context option.
CreateBrowserContextOption is a BrowserContext creation options.
DialOption is a dial option.
EmulateAction are actions that change the emulation settings for the browser.
EmulateViewportOption is the type for emulate viewport options.
Error is a chromedp error.
EvaluateAction are actions that evaluate JavaScript expressions using runtime.Evaluate.
EvaluateOption is the type for JavaScript evaluation options.
ExecAllocatorOption is an exec allocator option.
KeyAction are keyboard (key) input event actions.
KeyOption is a key action option.
MouseAction are mouse input event actions.
MouseOption is a mouse action option.
NavigateAction are actions which always trigger a page navigation, waiting for the page to load.
PollAction are actions that will wait for a general JavaScript predicate.
PollOption is a poll task option.
QueryAction are element query actions that select node elements from the browser's DOM for retrieval or manipulation.
QueryOption is an element query action option.
RemoteAllocatorOption is a remote allocator option.
Tasks is a sequential list of Actions that can be used as a single Action.