remote

package
v0.24.1 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2026 License: MIT Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package remote connects chromedp to a browser with a websocket. It holds the websocket connection, the allocator for a browser that runs already, the websocket mode of the exec allocator and the option that keeps a browser open. The package has its own WebSocket client, so it needs no library other than the standard library and cdproto. The pipe transport of the core does not import it.

Use NewAllocator to attach to a browser that runs already, for example a hosted browser service or a container. Use WebSocket to make the exec allocator of chromedp connect with a websocket, and WithKeepOpen to leave the browser open when the program ends.

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrInvalidMessage = errors.New("invalid websocket message")

ErrInvalidMessage is the error of a websocket frame that is neither a text frame nor a control frame.

Functions

func NewAllocator

func NewAllocator(parent context.Context, url string, opts ...Option) (context.Context, context.CancelFunc)

NewAllocator creates a new context with an Allocator. Use it with chromedp.NewContext. The url must point to the websocket address of the browser, such as "ws://127.0.0.1:$PORT/devtools/browser/...".

If the url does not contain "/devtools/browser/", NewAllocator tries to find the correct url. It sends a request to "http://$HOST:$PORT/json/version".

NewAllocator accepts urls of these formats:

It does not accept "ws://127.0.0.1:9222/devtools/browser/", because the allocator does not try to modify it and it is invalid.

Use NoModifyURL to stop NewAllocator from changing the url.

Example

This example attaches to a browser that an earlier program left open.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/chromedp/chromedp"
	"github.com/chromedp/chromedp/remote"
)

func main() {
	wsURL := os.Args[1] // the address that the earlier program printed

	allocCtx, cancel := remote.NewAllocator(context.Background(), wsURL)
	defer cancel()
	ctx, cancel := chromedp.NewContext(allocCtx)
	defer cancel()

	title, err := chromedp.Run(ctx, chromedp.Title())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(title)
}

func NoModifyURL

func NoModifyURL(a *Allocator)

NoModifyURL is an Option that prevents the allocator from modifying the websocket debugger URL passed to it.

func WebSocket

func WebSocket(a *chromedp.ExecAllocator)

WebSocket is a chromedp.ExecAllocatorOption that makes the exec allocator connect to the browser with a websocket, as chromedp did before the pipe became the default. The default is a pipe: the allocator starts the browser with --remote-debugging-pipe, and the browser reads the commands from a pipe and writes the responses and the events to another pipe. On Unix they are the file descriptors 3 and 4, and on Windows they are two handles. A pipe needs no port.

Use WebSocket when the browser must open a debugging port, for example to let a second program connect to it. The Flag options "remote-debugging-port" and "remote-debugging-address" also select the websocket, and they need this option. The option is also required for chromedp.KeepOpen.

For example:

opts := append(chromedp.DefaultExecAllocatorOptions[:], remote.WebSocket)
ctx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
Example

This example makes the exec allocator connect with a websocket. The browser then opens a debugging port and writes the file DevToolsActivePort in its user data directory.

package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"time"

	"github.com/chromedp/chromedp"
	"github.com/chromedp/chromedp/remote"
)

func main() {
	dir, err := os.MkdirTemp("", "chromedp-example")
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		// The child processes of Chrome can still write in the directory for
		// a short time after the browser stops. Then RemoveAll fails with
		// "directory not empty", so try again.
		for range 50 {
			if err := os.RemoveAll(dir); err == nil {
				return
			}
			time.Sleep(100 * time.Millisecond)
		}
	}()

	opts := append(chromedp.DefaultExecAllocatorOptions[:],
		chromedp.DisableGPU,
		chromedp.UserDataDir(dir),
		// Chrome writes the DevToolsActivePort file only when it opens
		// a debugging port, so this example uses the websocket mode.
		remote.WebSocket,
	)

	allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancel()

	// also set up a custom logger
	taskCtx, cancel := chromedp.NewContext(allocCtx, chromedp.WithLogf(log.Printf))
	defer cancel()

	// make sure that the browser process is started
	if err := chromedp.Do(taskCtx); err != nil {
		log.Fatal(err)
	}

	path := filepath.Join(dir, "DevToolsActivePort")
	bs, err := os.ReadFile(path)
	if err != nil {
		log.Fatal(err)
	}
	lines := bytes.Split(bs, []byte("\n"))
	fmt.Printf("DevToolsActivePort has %d lines\n", len(lines))

}
Output:
DevToolsActivePort has 2 lines

func WithKeepOpen

func WithKeepOpen() chromedp.ContextOption

WithKeepOpen makes chromedp.NewContext build the default allocator with chromedp.KeepOpen and with WebSocket. The browser then stays open when the program ends or when the context is canceled. It works with headless mode too. See also chromedp.KeptOpen and chromedp.WithVisibleWindow.

The option only applies when the parent context has no allocator. It has no effect on an allocator that the caller made, and it has no effect on a context that inherits a browser. For an allocator that you make, add chromedp.KeepOpen and WebSocket to the options of chromedp.NewExecAllocator instead.

Example

This example leaves the browser open when the program ends. The program prints the address, so that another program can attach with NewAllocator. The profile directory stays on disk, and the user must delete it.

package main

import (
	"context"
	"fmt"
	"log"

	"github.com/chromedp/chromedp"
	"github.com/chromedp/chromedp/remote"
)

func main() {
	ctx, cancel := chromedp.NewContext(context.Background(),
		chromedp.WithVisibleWindow(), remote.WithKeepOpen())
	defer cancel()

	if err := chromedp.Do(ctx, chromedp.Navigate("https://example.com")); err != nil {
		log.Fatal(err)
	}
	wsURL, profile := chromedp.KeptOpen(ctx)
	fmt.Println("attach to", wsURL)
	fmt.Println("profile directory", profile)
}

Types

type Allocator

type Allocator struct {
	// contains filtered or unexported fields
}

Allocator is a chromedp.Allocator which connects to an already running Chrome process through a websocket URL.

func (*Allocator) Allocate

func (a *Allocator) Allocate(ctx context.Context, opts ...chromedp.BrowserOption) (*chromedp.Browser, error)

Allocate satisfies the chromedp.Allocator interface.

func (*Allocator) Attaches

func (a *Allocator) Attaches() bool

Attaches satisfies the chromedp.Attacher interface. It always returns true, because the allocator connects to a browser that runs already.

func (*Allocator) Wait

func (a *Allocator) Wait()

Wait satisfies the chromedp.Allocator interface.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn implements chromedp.Transport with a websocket connection. The client is in the package remote/internal/websocket.

func DialContext

func DialContext(ctx context.Context, urlstr string, opts ...DialOption) (*Conn, error)

DialContext dials the websocket URL.

func (*Conn) Close

func (c *Conn) Close() error

Close satisfies the io.Closer interface.

func (*Conn) Read

func (c *Conn) Read(_ context.Context, msg *cdproto.Message) error

Read reads the next message. It answers a ping frame with a pong frame and skips a pong frame, as RFC 6455 section 5.5 requires. A server can send a ping at any time to check the connection. The method returns only when it has a text message or an error.

func (*Conn) SetDebugf

func (c *Conn) SetDebugf(f func(string, ...any))

SetDebugf sets the protocol logger. chromedp.NewBrowserTransport calls it with the logger of the browser.

func (*Conn) Write

func (c *Conn) Write(_ context.Context, msg *cdproto.Message) error

Write writes a message.

type DialOption

type DialOption = func(*Conn)

DialOption is a dial option.

func WithConnDebugf

func WithConnDebugf(f func(string, ...any)) DialOption

WithConnDebugf is a dial option to set a protocol logger.

func WithConnHTTPHeader

func WithConnHTTPHeader(h http.Header) DialOption

WithConnHTTPHeader is a dial option that sets HTTP headers on the websocket handshake request. For example, a hosted browser service can need an Authorization header. The option copies the header, so a later change of h has no effect.

type Option

type Option = func(*Allocator)

Option is an option of an Allocator.

func WithDialHTTPHeader

func WithDialHTTPHeader(h http.Header) Option

WithDialHTTPHeader is an Option that sets HTTP headers on the websocket handshake request to the remote browser. A hosted browser service can need an Authorization header. The option copies the header, so a later change of h has no effect.

The headers go with the websocket request only. The request to "/json/version", which NewAllocator sends to find the websocket address, has no headers. When the service needs headers, give it the full websocket address and use NoModifyURL. For example:

remote.NewAllocator(ctx, wsURL, remote.NoModifyURL,
	remote.WithDialHTTPHeader(http.Header{
		"Authorization": {"Bearer " + token},
	}))
Example

This example connects to a hosted browser service that needs an Authorization header on the websocket request.

package main

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/chromedp/chromedp"
	"github.com/chromedp/chromedp/remote"
)

func main() {
	const wsURL = "wss://browser.example.com/devtools/browser/id"
	header := http.Header{"Authorization": {"Bearer " + os.Getenv("BROWSER_TOKEN")}}

	allocCtx, cancel := remote.NewAllocator(context.Background(), wsURL,
		remote.NoModifyURL,
		remote.WithDialHTTPHeader(header),
	)
	defer cancel()
	ctx, cancel := chromedp.NewContext(allocCtx)
	defer cancel()

	title, err := chromedp.Run(ctx, chromedp.Title())
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(title)
}

func WithDialTimeout

func WithDialTimeout(d time.Duration) Option

WithDialTimeout is an Option that sets the timeout for the dial of the websocket address of the browser. The default is ten seconds. Use a zero duration for no timeout.

Directories

Path Synopsis
internal
websocket
Package websocket is a WebSocket client as RFC 6455 defines it.
Package websocket is a WebSocket client as RFC 6455 defines it.
wstest
Package wstest is a minimal WebSocket server for tests.
Package wstest is a minimal WebSocket server for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL