Playwright.Browser (Playwright v1.65.0-rc.3)

Copy Markdown View Source

A Browser is created via Playwright.BrowserType.launch/2. An example of using a Browser to create a Page:

# Or Playwright.chromium/1 or Playwright.webkit/1.
browser = BrowserType.launch!(Playwright.firefox(playwright))
page = Browser.new_page!(browser)
Page.goto!(page, "https://example.com")
Browser.close!(browser)

Since Playwright 1.8.

The examples alias the modules they use (alias Playwright.{Locator, Page}).

Events

:context

Since Playwright 1.60. Emitted when a new browser context is created.

:disconnected

Emitted when Browser gets disconnected from the browser application. This might happen because of one of the following:

Summary

Types

Options of bind/3, see its docs.

Options of close/2, see its docs.

An event name, see the module docs.

Options of new_context/2, see its docs.

Options of new_page/2, see its docs.

Options of start_tracing/3, see its docs.

t()

A Browser handle. Compare handles with ==, their fields are internal.

Functions

Binds the browser to a named pipe or web socket, making it available for other clients to connect to.

Like bind/3, but returns the value and raises on error.

Get the browser type (chromium, firefox or webkit) that the browser belongs to.

In case this browser is obtained using Playwright.BrowserType.launch/2, closes the browser and all of its pages (if any were opened).

Like close/2, but returns the value and raises on error.

Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.

Indicates that the browser is connected.

Like new_browser_cdp_session/1, but returns the value and raises on error.

Creates a new browser context. It won't share cookies/cache with other browser contexts.

Like new_context/2, but returns the value and raises on error.

Creates a new page in a new browser context. Closing this page will close the context as well.

Like new_page/2, but returns the value and raises on error.

Removes all the listeners of the given type (or all registered listeners if no type given). Allows to wait for running listeners to complete or to ignore subsequent errors from these listeners.

Like start_tracing/3, but returns the value and raises on error.

Like stop_tracing/1, but returns the value and raises on error.

Unbinds the browser server previously bound with Playwright.Browser.bind/3.

Like unbind/1, but returns the value and raises on error.

Returns the browser version.

Events

Adds an event listener for event, see the module docs for the events.

Removes an event listener added by on/3 or add_listener/3.

Adds an event listener for event, see the module docs for the events.

Adds an event listener that is removed after it is triggered once. See on/3.

Adds an event listener for event, see the module docs for the events.

Removes an event listener added by on/3 or add_listener/3.

Types

bind_options()

@type bind_options() ::
  [
    host: String.t(),
    metadata: %{optional(String.t()) => term()},
    port: integer(),
    workspace_dir: String.t()
  ]
  | %{
      optional(:host) => String.t(),
      optional(:metadata) => %{optional(String.t()) => term()},
      optional(:port) => integer(),
      optional(:workspace_dir) => String.t()
    }

Options of bind/3, see its docs.

close_options()

@type close_options() :: [{:reason, String.t()}] | %{optional(:reason) => String.t()}

Options of close/2, see its docs.

event()

@type event() :: :context | :disconnected

An event name, see the module docs.

new_context_options()

@type new_context_options() ::
  [
    accept_downloads: boolean(),
    base_url: String.t(),
    bypass_csp: boolean(),
    client_certificates: [
      %{
        :origin => String.t(),
        optional(:certPath) => String.t(),
        optional(:cert) => binary(),
        optional(:keyPath) => String.t(),
        optional(:key) => binary(),
        optional(:pfxPath) => String.t(),
        optional(:pfx) => binary(),
        optional(:passphrase) => String.t()
      }
    ],
    color_scheme: :null | :light | :dark | :no_preference,
    contrast: :null | :no_preference | :more,
    device_scale_factor: number(),
    extra_http_headers: %{optional(String.t()) => String.t()},
    forced_colors: :null | :active | :none,
    geolocation: %{
      :latitude => number(),
      :longitude => number(),
      optional(:accuracy) => number()
    },
    has_touch: boolean(),
    http_credentials:
      %{
        :username => String.t(),
        :password => String.t(),
        optional(:origin) => String.t(),
        optional(:send) => String.t()
      }
      | [
          %{
            :username => String.t(),
            :password => String.t(),
            optional(:origin) => String.t(),
            optional(:send) => String.t()
          }
        ],
    ignore_https_errors: boolean(),
    is_mobile: boolean(),
    java_script_enabled: boolean(),
    locale: String.t(),
    logger: %{
      isEnabled: (String.t(), String.t() -> boolean()),
      log: (String.t(),
            String.t(),
            String.t()
            | Exception.t(),
            [map()],
            %{optional(:color) => String.t()} ->
              term())
    },
    offline: boolean(),
    permissions: [String.t()],
    proxy: %{
      :server => String.t(),
      optional(:bypass) => String.t(),
      optional(:username) => String.t(),
      optional(:password) => String.t()
    },
    record_har: %{
      optional(:omitContent) => boolean(),
      optional(:content) => String.t(),
      :path => String.t(),
      optional(:mode) => String.t(),
      optional(:urlFilter) => String.t() | Regex.t() | Playwright.RegExp.t()
    },
    record_video: %{
      optional(:dir) => String.t(),
      optional(:size) => %{width: integer(), height: integer()},
      optional(:fps) => integer(),
      optional(:showActions) => %{
        optional(:duration) => number(),
        optional(:position) => String.t(),
        optional(:fontSize) => integer(),
        optional(:cursor) => String.t(),
        optional(:style) => %{
          optional(:point) => String.t(),
          optional(:highlight) => String.t(),
          optional(:title) => String.t()
        }
      }
    },
    reduced_motion: :null | :reduce | :no_preference,
    screen: %{width: integer(), height: integer()},
    service_workers: :allow | :block,
    storage_state: String.t() | map(),
    strict_selectors: boolean(),
    timezone_id: String.t(),
    user_agent: String.t(),
    viewport: :null | %{width: integer(), height: integer()},
    default_browser_type: String.t()
  ]
  | %{
      optional(:accept_downloads) => boolean(),
      optional(:base_url) => String.t(),
      optional(:bypass_csp) => boolean(),
      optional(:client_certificates) => [
        %{
          :origin => String.t(),
          optional(:certPath) => String.t(),
          optional(:cert) => binary(),
          optional(:keyPath) => String.t(),
          optional(:key) => binary(),
          optional(:pfxPath) => String.t(),
          optional(:pfx) => binary(),
          optional(:passphrase) => String.t()
        }
      ],
      optional(:color_scheme) => :null | :light | :dark | :no_preference,
      optional(:contrast) => :null | :no_preference | :more,
      optional(:device_scale_factor) => number(),
      optional(:extra_http_headers) => %{optional(String.t()) => String.t()},
      optional(:forced_colors) => :null | :active | :none,
      optional(:geolocation) => %{
        :latitude => number(),
        :longitude => number(),
        optional(:accuracy) => number()
      },
      optional(:has_touch) => boolean(),
      optional(:http_credentials) =>
        %{
          :username => String.t(),
          :password => String.t(),
          optional(:origin) => String.t(),
          optional(:send) => String.t()
        }
        | [
            %{
              :username => String.t(),
              :password => String.t(),
              optional(:origin) => String.t(),
              optional(:send) => String.t()
            }
          ],
      optional(:ignore_https_errors) => boolean(),
      optional(:is_mobile) => boolean(),
      optional(:java_script_enabled) => boolean(),
      optional(:locale) => String.t(),
      optional(:logger) => %{
        isEnabled: (String.t(), String.t() -> boolean()),
        log: (String.t(),
              String.t(),
              String.t()
              | Exception.t(),
              [map()],
              %{optional(:color) => String.t()} ->
                term())
      },
      optional(:offline) => boolean(),
      optional(:permissions) => [String.t()],
      optional(:proxy) => %{
        :server => String.t(),
        optional(:bypass) => String.t(),
        optional(:username) => String.t(),
        optional(:password) => String.t()
      },
      optional(:record_har) => %{
        optional(:omitContent) => boolean(),
        optional(:content) => String.t(),
        :path => String.t(),
        optional(:mode) => String.t(),
        optional(:urlFilter) => String.t() | Regex.t() | Playwright.RegExp.t()
      },
      optional(:record_video) => %{
        optional(:dir) => String.t(),
        optional(:size) => %{width: integer(), height: integer()},
        optional(:fps) => integer(),
        optional(:showActions) => %{
          optional(:duration) => number(),
          optional(:position) => String.t(),
          optional(:fontSize) => integer(),
          optional(:cursor) => String.t(),
          optional(:style) => %{
            optional(:point) => String.t(),
            optional(:highlight) => String.t(),
            optional(:title) => String.t()
          }
        }
      },
      optional(:reduced_motion) => :null | :reduce | :no_preference,
      optional(:screen) => %{width: integer(), height: integer()},
      optional(:service_workers) => :allow | :block,
      optional(:storage_state) => String.t() | map(),
      optional(:strict_selectors) => boolean(),
      optional(:timezone_id) => String.t(),
      optional(:user_agent) => String.t(),
      optional(:viewport) => :null | %{width: integer(), height: integer()},
      optional(:default_browser_type) => String.t()
    }

Options of new_context/2, see its docs.

new_page_options()

@type new_page_options() ::
  [
    accept_downloads: boolean(),
    base_url: String.t(),
    bypass_csp: boolean(),
    client_certificates: [
      %{
        :origin => String.t(),
        optional(:certPath) => String.t(),
        optional(:cert) => binary(),
        optional(:keyPath) => String.t(),
        optional(:key) => binary(),
        optional(:pfxPath) => String.t(),
        optional(:pfx) => binary(),
        optional(:passphrase) => String.t()
      }
    ],
    color_scheme: :null | :light | :dark | :no_preference,
    contrast: :null | :no_preference | :more,
    device_scale_factor: number(),
    extra_http_headers: %{optional(String.t()) => String.t()},
    forced_colors: :null | :active | :none,
    geolocation: %{
      :latitude => number(),
      :longitude => number(),
      optional(:accuracy) => number()
    },
    has_touch: boolean(),
    http_credentials:
      %{
        :username => String.t(),
        :password => String.t(),
        optional(:origin) => String.t(),
        optional(:send) => String.t()
      }
      | [
          %{
            :username => String.t(),
            :password => String.t(),
            optional(:origin) => String.t(),
            optional(:send) => String.t()
          }
        ],
    ignore_https_errors: boolean(),
    is_mobile: boolean(),
    java_script_enabled: boolean(),
    locale: String.t(),
    logger: %{
      isEnabled: (String.t(), String.t() -> boolean()),
      log: (String.t(),
            String.t(),
            String.t()
            | Exception.t(),
            [map()],
            %{optional(:color) => String.t()} ->
              term())
    },
    offline: boolean(),
    permissions: [String.t()],
    proxy: %{
      :server => String.t(),
      optional(:bypass) => String.t(),
      optional(:username) => String.t(),
      optional(:password) => String.t()
    },
    record_har: %{
      optional(:omitContent) => boolean(),
      optional(:content) => String.t(),
      :path => String.t(),
      optional(:mode) => String.t(),
      optional(:urlFilter) => String.t() | Regex.t() | Playwright.RegExp.t()
    },
    record_video: %{
      optional(:dir) => String.t(),
      optional(:size) => %{width: integer(), height: integer()},
      optional(:fps) => integer(),
      optional(:showActions) => %{
        optional(:duration) => number(),
        optional(:position) => String.t(),
        optional(:fontSize) => integer(),
        optional(:cursor) => String.t(),
        optional(:style) => %{
          optional(:point) => String.t(),
          optional(:highlight) => String.t(),
          optional(:title) => String.t()
        }
      }
    },
    reduced_motion: :null | :reduce | :no_preference,
    screen: %{width: integer(), height: integer()},
    service_workers: :allow | :block,
    storage_state: String.t() | map(),
    strict_selectors: boolean(),
    timezone_id: String.t(),
    user_agent: String.t(),
    viewport: :null | %{width: integer(), height: integer()},
    default_browser_type: String.t()
  ]
  | %{
      optional(:accept_downloads) => boolean(),
      optional(:base_url) => String.t(),
      optional(:bypass_csp) => boolean(),
      optional(:client_certificates) => [
        %{
          :origin => String.t(),
          optional(:certPath) => String.t(),
          optional(:cert) => binary(),
          optional(:keyPath) => String.t(),
          optional(:key) => binary(),
          optional(:pfxPath) => String.t(),
          optional(:pfx) => binary(),
          optional(:passphrase) => String.t()
        }
      ],
      optional(:color_scheme) => :null | :light | :dark | :no_preference,
      optional(:contrast) => :null | :no_preference | :more,
      optional(:device_scale_factor) => number(),
      optional(:extra_http_headers) => %{optional(String.t()) => String.t()},
      optional(:forced_colors) => :null | :active | :none,
      optional(:geolocation) => %{
        :latitude => number(),
        :longitude => number(),
        optional(:accuracy) => number()
      },
      optional(:has_touch) => boolean(),
      optional(:http_credentials) =>
        %{
          :username => String.t(),
          :password => String.t(),
          optional(:origin) => String.t(),
          optional(:send) => String.t()
        }
        | [
            %{
              :username => String.t(),
              :password => String.t(),
              optional(:origin) => String.t(),
              optional(:send) => String.t()
            }
          ],
      optional(:ignore_https_errors) => boolean(),
      optional(:is_mobile) => boolean(),
      optional(:java_script_enabled) => boolean(),
      optional(:locale) => String.t(),
      optional(:logger) => %{
        isEnabled: (String.t(), String.t() -> boolean()),
        log: (String.t(),
              String.t(),
              String.t()
              | Exception.t(),
              [map()],
              %{optional(:color) => String.t()} ->
                term())
      },
      optional(:offline) => boolean(),
      optional(:permissions) => [String.t()],
      optional(:proxy) => %{
        :server => String.t(),
        optional(:bypass) => String.t(),
        optional(:username) => String.t(),
        optional(:password) => String.t()
      },
      optional(:record_har) => %{
        optional(:omitContent) => boolean(),
        optional(:content) => String.t(),
        :path => String.t(),
        optional(:mode) => String.t(),
        optional(:urlFilter) => String.t() | Regex.t() | Playwright.RegExp.t()
      },
      optional(:record_video) => %{
        optional(:dir) => String.t(),
        optional(:size) => %{width: integer(), height: integer()},
        optional(:fps) => integer(),
        optional(:showActions) => %{
          optional(:duration) => number(),
          optional(:position) => String.t(),
          optional(:fontSize) => integer(),
          optional(:cursor) => String.t(),
          optional(:style) => %{
            optional(:point) => String.t(),
            optional(:highlight) => String.t(),
            optional(:title) => String.t()
          }
        }
      },
      optional(:reduced_motion) => :null | :reduce | :no_preference,
      optional(:screen) => %{width: integer(), height: integer()},
      optional(:service_workers) => :allow | :block,
      optional(:storage_state) => String.t() | map(),
      optional(:strict_selectors) => boolean(),
      optional(:timezone_id) => String.t(),
      optional(:user_agent) => String.t(),
      optional(:viewport) => :null | %{width: integer(), height: integer()},
      optional(:default_browser_type) => String.t()
    }

Options of new_page/2, see its docs.

remove_all_listeners_options()

@type remove_all_listeners_options() ::
  [{:behavior, :wait | :ignore_errors | :default}]
  | %{optional(:behavior) => :wait | :ignore_errors | :default}

Options of remove_all_listeners/3, see its docs.

start_tracing_options()

@type start_tracing_options() ::
  [categories: [String.t()], path: String.t(), screenshots: boolean()]
  | %{
      optional(:categories) => [String.t()],
      optional(:path) => String.t(),
      optional(:screenshots) => boolean()
    }

Options of start_tracing/3, see its docs.

t()

@type t() :: %Playwright.Browser{
  conn: term(),
  guid: term(),
  initializer: term(),
  table: term(),
  type: term()
}

A Browser handle. Compare handles with ==, their fields are internal.

Functions

bind(browser, title, options \\ [])

@spec bind(t(), String.t(), bind_options()) ::
  {:ok, %{endpoint: String.t()}} | {:error, Playwright.error()}

Binds the browser to a named pipe or web socket, making it available for other clients to connect to.

Since Playwright 1.59.

Arguments

  • title - Title of the browser server, used for identification.

Options

  • :host (String.t/0) - Host to bind the web socket server to. When specified, a web socket server is created instead of a named pipe.
  • :metadata (%{optional(String.t()) => term()}) - Additional metadata to associate with the browser server.
  • :port (integer/0) - Port to bind the web socket server to. When specified, a web socket server is created instead of a named pipe. Use 0 to let the OS pick an available port.
  • :workspace_dir (String.t/0) - Working directory associated with this browser server.

bind!(browser, title, options \\ [])

@spec bind!(t(), String.t(), bind_options()) :: %{endpoint: String.t()}

Like bind/3, but returns the value and raises on error.

browser_type(browser)

@spec browser_type(t()) :: Playwright.BrowserType.t()

Get the browser type (chromium, firefox or webkit) that the browser belongs to.

Since Playwright 1.23.

close(browser, options \\ [])

@spec close(t(), close_options()) :: :ok | {:error, Playwright.error()}

In case this browser is obtained using Playwright.BrowserType.launch/2, closes the browser and all of its pages (if any were opened).

In case this browser is connected to, clears all created contexts belonging to this browser and disconnects from the browser server.

Note

This is similar to force-quitting the browser. To close pages gracefully and ensure you receive page close events, call Playwright.BrowserContext.close/2 on any BrowserContext instances you explicitly created earlier using Playwright.Browser.new_context/2 before calling Playwright.Browser.close/2.

The Browser object itself is considered to be disposed and cannot be used anymore.

Since Playwright 1.8.

Options

  • :reason (String.t/0) - Since Playwright 1.40. The reason to be reported to the operations interrupted by the browser closure.

close!(browser, options \\ [])

@spec close!(t(), close_options()) :: :ok

Like close/2, but returns the value and raises on error.

contexts(browser)

@spec contexts(t()) :: [Playwright.BrowserContext.t()]

Returns an array of all open browser contexts. In a newly created browser, this will return zero browser contexts.

Usage

browser = BrowserType.launch!(Playwright.webkit(playwright))
# prints 0
IO.puts(length(Browser.contexts(browser)))

context = Browser.new_context!(browser)
# prints 1
IO.puts(length(Browser.contexts(browser)))

Since Playwright 1.8.

is_connected(browser)

@spec is_connected(t()) :: boolean()

Indicates that the browser is connected.

Since Playwright 1.8.

new_browser_cdp_session(browser)

@spec new_browser_cdp_session(t()) ::
  {:ok, Playwright.CDPSession.t()} | {:error, Playwright.error()}

Note

CDP Sessions are only supported on Chromium-based browsers.

Returns the newly created browser session.

Since Playwright 1.11.

new_browser_cdp_session!(browser)

@spec new_browser_cdp_session!(t()) :: Playwright.CDPSession.t()

Like new_browser_cdp_session/1, but returns the value and raises on error.

new_context(browser, options \\ [])

@spec new_context(t(), new_context_options()) ::
  {:ok, Playwright.BrowserContext.t()} | {:error, Playwright.error()}

Creates a new browser context. It won't share cookies/cache with other browser contexts.

Note

If directly using this method to create BrowserContexts, it is best practice to explicitly close the returned context via Playwright.BrowserContext.close/2 when your code is done with the BrowserContext, and before calling Playwright.Browser.close/2. This will ensure the context is closed gracefully and any artifacts—like HARs and videos—are fully flushed and saved.

Usage

# Or Playwright.chromium/1 or Playwright.webkit/1.
browser = BrowserType.launch!(Playwright.firefox(playwright))
# Create a new incognito browser context.
context = Browser.new_context!(browser)
# Create a new page in a pristine context.
page = BrowserContext.new_page!(context)
Page.goto!(page, "https://example.com")

# Gracefully close up everything
BrowserContext.close!(context)
Browser.close!(browser)

Since Playwright 1.8.

Options

  • :accept_downloads (boolean/0) - Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.
  • :base_url (String.t/0) - When using Playwright.Page.goto/3, Playwright.Page.route/4, Playwright.Page.wait_for_url/3, Playwright.Page.wait_for_request/3, or Playwright.Page.wait_for_response/3 it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:
    • baseURL: http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html
    • baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html
    • baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html
  • :bypass_csp (boolean/0) - Toggles bypassing page's Content-Security-Policy. Defaults to false.
  • :client_certificates (list of map/0) - Since Playwright 1.46. TLS Client Authentication allows the server to request a client certificate and verify it.DetailsAn array of client certificates to be used. Each certificate object must have either both certPath and keyPath, a single pfxPath, or their corresponding direct value equivalents (cert and key, or pfx). Optionally, passphrase property should be provided if the certificate is encrypted. The origin property should be provided with an exact match to the request origin that the certificate is valid for.Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an origin that does not match any of the domains you plan to visit.

    Note

    When using WebKit on macOS, accessing localhost will not pick up client certificates. You can make it work by replacing localhost with local.playwright.

    • :origin - Exact origin that the certificate is valid for. Origin includes https protocol, a hostname and optionally a port.
    • :certPath - Path to the file with the certificate in PEM format.
    • :cert - Direct value of the certificate in PEM format.
    • :keyPath - Path to the file with the private key in PEM format.
    • :key - Direct value of the private key in PEM format.
    • :pfxPath - Path to the PFX or PKCS12 encoded private key and certificate chain.
    • :pfx - Direct value of the PFX or PKCS12 encoded private key and certificate chain.
    • :passphrase - Passphrase for the private key (PEM or PFX).
  • :color_scheme (:null | :light | :dark | :no_preference) - Emulates prefers-colors-scheme media feature, supported values are :light and :dark. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :light.

  • :contrast (:null | :no_preference | :more) - Emulates 'prefers-contrast' media feature, supported values are :no_preference, :more. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :no_preference.

  • :device_scale_factor (number/0) - Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.
  • :extra_http_headers (%{optional(String.t()) => String.t()}) - An object containing additional HTTP headers to be sent with every request. Defaults to none.
  • :forced_colors (:null | :active | :none) - Emulates 'forced-colors' media feature, supported values are :active, :none. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :none.

  • :geolocation (map/0)
    • :latitude - Latitude between -90 and 90.
    • :longitude - Longitude between -180 and 180.
    • :accuracy - Non-negative accuracy value. Defaults to 0.
  • :has_touch (boolean/0) - Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
  • :http_credentials (map/0 | list of map/0) - Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

    Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request.
    • :username
    • :password
    • :origin - Restrain sending http credentials on specific origin (scheme://host:port).
    • :send - This option only applies to the requests sent from corresponding APIRequestContext and does not affect requests sent from the browser. 'always' - Authorization header with basic authentication credentials will be sent with the each API request. 'unauthorized - the credentials are only sent when 401 (Unauthorized) response with WWW-Authenticate header is received. Defaults to 'unauthorized'.
  • :ignore_https_errors (boolean/0) - Whether to ignore HTTPS errors when sending network requests. Defaults to false.
  • :is_mobile (boolean/0) - Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false. Learn more about mobile emulation.
  • :java_script_enabled (boolean/0) - Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.
  • :locale (String.t/0) - Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. Defaults to the system default locale. Learn more about emulation in our emulation guide.
  • :logger (map/0) - Logger sink for Playwright logging.
    • :isEnabled - Determines whether sink is interested in the logger with the given name and severity.
    • :log
  • :offline (boolean/0) - Whether to emulate network being offline. Defaults to false. Learn more about network emulation.
  • :permissions (list of String.t/0) - A list of permissions to grant to all pages in this context. See Playwright.BrowserContext.grant_permissions/3 for more details. Defaults to none.
  • :proxy (map/0) - Network proxy settings to use with this context. Defaults to none.
    • :server - Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.
    • :bypass - Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".
    • :username - Optional username to use if HTTP proxy requires authentication.
    • :password - Optional password to use if HTTP proxy requires authentication.
  • :record_har (map/0) - Enables HAR recording for all pages into recordHar.path file. If not specified, the HAR is not recorded. Make sure to call Playwright.BrowserContext.close/2 for the HAR to be saved.
    • :omitContent - Optional setting to control whether to omit request content from the HAR. Defaults to false. Deprecated, use content policy instead.
    • :content - Optional setting to control resource content management. If omit is specified, content is not persisted. If attach is specified, resources are persisted as separate files or entries in the ZIP archive. If embed is specified, content is stored inline the HAR file as per HAR specification. Defaults to attach for .zip output files and to embed for all other file extensions.
    • :path - Path on the filesystem to write the HAR file to. If the file name ends with .zip, content: 'attach' is used by default.
    • :mode - When set to minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to full.
    • :urlFilter - A glob or regex pattern to filter requests that are stored in the HAR. When a :base_url via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor. Defaults to none.
  • :record_video (map/0) - Enables video recording for all pages into recordVideo.dir directory. If not specified videos are not recorded. Make sure to call Playwright.BrowserContext.close/2 for videos to be saved.
    • :dir - Path to the directory to put videos into. If not specified, the videos will be stored in :artifacts_dir (see Playwright.BrowserType.launch/2 options).
    • :size - Optional dimensions of the recorded videos. If not specified the size will be equal to :viewport scaled down to fit into 800x800. If :viewport is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.
      • :width - Video frame width.
      • :height - Video frame height.
    • :fps - Frame rate of the recorded videos in frames per second. Defaults to 25. Firefox and WebKit currently capture up to 25 frames per second.
    • :showActions - If specified, enables visual annotations on interacted elements during video recording.
      • :duration - How long each annotation is displayed in milliseconds. Defaults to 500.
      • :position - Position of the action title overlay. Defaults to "top-right".
      • :fontSize - Font size of the action title in pixels. Defaults to 24. Deprecated, use style.title instead.
      • :cursor - Cursor decoration shown for pointer actions. "pointer" (the default) renders a mouse pointer that animates from the previous action point to the next one. "none" disables the cursor decoration.
      • :style - Styles of the action decorations.
        • :point - CSS declarations for the zero-sized marker centered on the action point. Not shown when omitted.
        • :highlight - CSS declarations for the box that covers the target element. Not shown when omitted.
        • :title - CSS declarations for the action title.
  • :reduced_motion (:null | :reduce | :no_preference) - Emulates 'prefers-reduced-motion' media feature, supported values are :reduce, :no_preference. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :no_preference.

  • :screen (map/0) - Emulates consistent window screen size available inside web page via window.screen. Is only used when the :viewport is set.
    • :width - page width in pixels.
    • :height - page height in pixels.
  • :service_workers (:allow | :block) - Whether to allow sites to register Service workers. Defaults to :allow.

    • :allow: Service Workers can be registered.
    • :block: Playwright will block all registration of Service Workers.
  • :storage_state (String.t/0 | map/0) - Learn more about storage state and auth.

    Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via Playwright.BrowserContext.storage_state/2.
    • :cookies - Cookies to set for context
      • :name
      • :value
      • :domain - Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com"
      • :path - Domain and path are required
      • :expires - Unix time in seconds.
      • :httpOnly
      • :secure
      • :sameSite - sameSite flag
    • :origins
      • :origin
      • :localStorage - localStorage to set for context
        • :name
        • :value
  • :strict_selectors (boolean/0) - If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors that imply single target DOM element will fail when more than one element matches the selector. This option does not affect any Locator APIs (Locators are always strict). Defaults to false. See Locator to learn more about the strict mode.
  • :timezone_id (String.t/0) - Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
  • :user_agent (String.t/0) - Specific user agent to use in this context.
  • :viewport (:null | map/0) - Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use :null to disable the consistent viewport emulation. Learn more about viewport emulation.

    Note

    The :null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic.

    • :width - page width in pixels.
    • :height - page height in pixels.
  • :default_browser_type (String.t/0) - Ignored: the browser type of a device descriptor (Playwright.devices/1), so one can be passed as options.

new_context!(browser, options \\ [])

@spec new_context!(t(), new_context_options()) :: Playwright.BrowserContext.t()

Like new_context/2, but returns the value and raises on error.

new_page(browser, options \\ [])

@spec new_page(t(), new_page_options()) ::
  {:ok, Playwright.Page.t()} | {:error, Playwright.error()}

Creates a new page in a new browser context. Closing this page will close the context as well.

This is a convenience API that should only be used for the single-page scenarios and short snippets. Production code and testing frameworks should explicitly create Playwright.Browser.new_context/2 followed by the Playwright.BrowserContext.new_page/1 to control their exact life times.

Since Playwright 1.8.

Options

  • :accept_downloads (boolean/0) - Whether to automatically download all the attachments. Defaults to true where all the downloads are accepted.
  • :base_url (String.t/0) - When using Playwright.Page.goto/3, Playwright.Page.route/4, Playwright.Page.wait_for_url/3, Playwright.Page.wait_for_request/3, or Playwright.Page.wait_for_response/3 it takes the base URL in consideration by using the URL() constructor for building the corresponding URL. Unset by default. Examples:
    • baseURL: http://localhost:3000 and navigating to /bar.html results in http://localhost:3000/bar.html
    • baseURL: http://localhost:3000/foo/ and navigating to ./bar.html results in http://localhost:3000/foo/bar.html
    • baseURL: http://localhost:3000/foo (without trailing slash) and navigating to ./bar.html results in http://localhost:3000/bar.html
  • :bypass_csp (boolean/0) - Toggles bypassing page's Content-Security-Policy. Defaults to false.
  • :client_certificates (list of map/0) - Since Playwright 1.46. TLS Client Authentication allows the server to request a client certificate and verify it.DetailsAn array of client certificates to be used. Each certificate object must have either both certPath and keyPath, a single pfxPath, or their corresponding direct value equivalents (cert and key, or pfx). Optionally, passphrase property should be provided if the certificate is encrypted. The origin property should be provided with an exact match to the request origin that the certificate is valid for.Client certificate authentication is only active when at least one client certificate is provided. If you want to reject all client certificates sent by the server, you need to provide a client certificate with an origin that does not match any of the domains you plan to visit.

    Note

    When using WebKit on macOS, accessing localhost will not pick up client certificates. You can make it work by replacing localhost with local.playwright.

    • :origin - Exact origin that the certificate is valid for. Origin includes https protocol, a hostname and optionally a port.
    • :certPath - Path to the file with the certificate in PEM format.
    • :cert - Direct value of the certificate in PEM format.
    • :keyPath - Path to the file with the private key in PEM format.
    • :key - Direct value of the private key in PEM format.
    • :pfxPath - Path to the PFX or PKCS12 encoded private key and certificate chain.
    • :pfx - Direct value of the PFX or PKCS12 encoded private key and certificate chain.
    • :passphrase - Passphrase for the private key (PEM or PFX).
  • :color_scheme (:null | :light | :dark | :no_preference) - Emulates prefers-colors-scheme media feature, supported values are :light and :dark. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :light.

  • :contrast (:null | :no_preference | :more) - Emulates 'prefers-contrast' media feature, supported values are :no_preference, :more. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :no_preference.

  • :device_scale_factor (number/0) - Specify device scale factor (can be thought of as dpr). Defaults to 1. Learn more about emulating devices with device scale factor.
  • :extra_http_headers (%{optional(String.t()) => String.t()}) - An object containing additional HTTP headers to be sent with every request. Defaults to none.
  • :forced_colors (:null | :active | :none) - Emulates 'forced-colors' media feature, supported values are :active, :none. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :none.

  • :geolocation (map/0)
    • :latitude - Latitude between -90 and 90.
    • :longitude - Longitude between -180 and 180.
    • :accuracy - Non-negative accuracy value. Defaults to 0.
  • :has_touch (boolean/0) - Specifies if viewport supports touch events. Defaults to false. Learn more about mobile emulation.
  • :http_credentials (map/0 | list of map/0) - Credentials for HTTP authentication. If no origin is specified, the username and password are sent to any servers upon unauthorized responses.

    Pass an array to use different credentials for different origins. The first entry that matches the request origin is used, and entries with no origin match any request.
    • :username
    • :password
    • :origin - Restrain sending http credentials on specific origin (scheme://host:port).
    • :send - This option only applies to the requests sent from corresponding APIRequestContext and does not affect requests sent from the browser. 'always' - Authorization header with basic authentication credentials will be sent with the each API request. 'unauthorized - the credentials are only sent when 401 (Unauthorized) response with WWW-Authenticate header is received. Defaults to 'unauthorized'.
  • :ignore_https_errors (boolean/0) - Whether to ignore HTTPS errors when sending network requests. Defaults to false.
  • :is_mobile (boolean/0) - Whether the meta viewport tag is taken into account and touch events are enabled. isMobile is a part of device, so you don't actually need to set it manually. Defaults to false. Learn more about mobile emulation.
  • :java_script_enabled (boolean/0) - Whether or not to enable JavaScript in the context. Defaults to true. Learn more about disabling JavaScript.
  • :locale (String.t/0) - Specify user locale, for example en-GB, de-DE, etc. Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules. Defaults to the system default locale. Learn more about emulation in our emulation guide.
  • :logger (map/0) - Logger sink for Playwright logging.
    • :isEnabled - Determines whether sink is interested in the logger with the given name and severity.
    • :log
  • :offline (boolean/0) - Whether to emulate network being offline. Defaults to false. Learn more about network emulation.
  • :permissions (list of String.t/0) - A list of permissions to grant to all pages in this context. See Playwright.BrowserContext.grant_permissions/3 for more details. Defaults to none.
  • :proxy (map/0) - Network proxy settings to use with this context. Defaults to none.
    • :server - Proxy to be used for all requests. HTTP and SOCKS proxies are supported, for example http://myproxy.com:3128 or socks5://myproxy.com:3128. Short form myproxy.com:3128 is considered an HTTP proxy.
    • :bypass - Optional comma-separated domains to bypass proxy, for example ".com, chromium.org, .domain.com".
    • :username - Optional username to use if HTTP proxy requires authentication.
    • :password - Optional password to use if HTTP proxy requires authentication.
  • :record_har (map/0) - Enables HAR recording for all pages into recordHar.path file. If not specified, the HAR is not recorded. Make sure to call Playwright.BrowserContext.close/2 for the HAR to be saved.
    • :omitContent - Optional setting to control whether to omit request content from the HAR. Defaults to false. Deprecated, use content policy instead.
    • :content - Optional setting to control resource content management. If omit is specified, content is not persisted. If attach is specified, resources are persisted as separate files or entries in the ZIP archive. If embed is specified, content is stored inline the HAR file as per HAR specification. Defaults to attach for .zip output files and to embed for all other file extensions.
    • :path - Path on the filesystem to write the HAR file to. If the file name ends with .zip, content: 'attach' is used by default.
    • :mode - When set to minimal, only record information necessary for routing from HAR. This omits sizes, timing, page, cookies, security and other types of HAR information that are not used when replaying from HAR. Defaults to full.
    • :urlFilter - A glob or regex pattern to filter requests that are stored in the HAR. When a :base_url via the context options was provided and the passed URL is a path, it gets merged via the new URL() constructor. Defaults to none.
  • :record_video (map/0) - Enables video recording for all pages into recordVideo.dir directory. If not specified videos are not recorded. Make sure to call Playwright.BrowserContext.close/2 for videos to be saved.
    • :dir - Path to the directory to put videos into. If not specified, the videos will be stored in :artifacts_dir (see Playwright.BrowserType.launch/2 options).
    • :size - Optional dimensions of the recorded videos. If not specified the size will be equal to :viewport scaled down to fit into 800x800. If :viewport is not configured explicitly the video size defaults to 800x450. Actual picture of each page will be scaled down if necessary to fit the specified size.
      • :width - Video frame width.
      • :height - Video frame height.
    • :fps - Frame rate of the recorded videos in frames per second. Defaults to 25. Firefox and WebKit currently capture up to 25 frames per second.
    • :showActions - If specified, enables visual annotations on interacted elements during video recording.
      • :duration - How long each annotation is displayed in milliseconds. Defaults to 500.
      • :position - Position of the action title overlay. Defaults to "top-right".
      • :fontSize - Font size of the action title in pixels. Defaults to 24. Deprecated, use style.title instead.
      • :cursor - Cursor decoration shown for pointer actions. "pointer" (the default) renders a mouse pointer that animates from the previous action point to the next one. "none" disables the cursor decoration.
      • :style - Styles of the action decorations.
        • :point - CSS declarations for the zero-sized marker centered on the action point. Not shown when omitted.
        • :highlight - CSS declarations for the box that covers the target element. Not shown when omitted.
        • :title - CSS declarations for the action title.
  • :reduced_motion (:null | :reduce | :no_preference) - Emulates 'prefers-reduced-motion' media feature, supported values are :reduce, :no_preference. See Playwright.Page.emulate_media/2 for more details. Passing :null resets emulation to system defaults. Defaults to :no_preference.

  • :screen (map/0) - Emulates consistent window screen size available inside web page via window.screen. Is only used when the :viewport is set.
    • :width - page width in pixels.
    • :height - page height in pixels.
  • :service_workers (:allow | :block) - Whether to allow sites to register Service workers. Defaults to :allow.

    • :allow: Service Workers can be registered.
    • :block: Playwright will block all registration of Service Workers.
  • :storage_state (String.t/0 | map/0) - Learn more about storage state and auth.

    Populates context with given storage state. This option can be used to initialize context with logged-in information obtained via Playwright.BrowserContext.storage_state/2.
    • :cookies - Cookies to set for context
      • :name
      • :value
      • :domain - Domain and path are required. For the cookie to apply to all subdomains as well, prefix domain with a dot, like this: ".example.com"
      • :path - Domain and path are required
      • :expires - Unix time in seconds.
      • :httpOnly
      • :secure
      • :sameSite - sameSite flag
    • :origins
      • :origin
      • :localStorage - localStorage to set for context
        • :name
        • :value
  • :strict_selectors (boolean/0) - If set to true, enables strict selectors mode for this context. In the strict selectors mode all operations on selectors that imply single target DOM element will fail when more than one element matches the selector. This option does not affect any Locator APIs (Locators are always strict). Defaults to false. See Locator to learn more about the strict mode.
  • :timezone_id (String.t/0) - Changes the timezone of the context. See ICU's metaZones.txt for a list of supported timezone IDs. Defaults to the system timezone.
  • :user_agent (String.t/0) - Specific user agent to use in this context.
  • :viewport (:null | map/0) - Emulates consistent viewport for each page. Defaults to an 1280x720 viewport. Use :null to disable the consistent viewport emulation. Learn more about viewport emulation.

    Note

    The :null value opts out from the default presets, makes viewport depend on the host window size defined by the operating system. It makes the execution of the tests non-deterministic.

    • :width - page width in pixels.
    • :height - page height in pixels.
  • :default_browser_type (String.t/0) - Ignored: the browser type of a device descriptor (Playwright.devices/1), so one can be passed as options.

new_page!(browser, options \\ [])

@spec new_page!(t(), new_page_options()) :: Playwright.Page.t()

Like new_page/2, but returns the value and raises on error.

remove_all_listeners(browser, event \\ nil, options \\ [])

@spec remove_all_listeners(
  t(),
  event() | String.t() | nil,
  remove_all_listeners_options()
) ::
  :ok | {:error, Playwright.error()}

Removes all the listeners of the given type (or all registered listeners if no type given). Allows to wait for running listeners to complete or to ignore subsequent errors from these listeners.

Since Playwright 1.47.

Options

The options may take the place of event, which is then nil.

  • :behavior (:wait | :ignore_errors | :default) - Specifies whether to wait for already running listeners and what to do if they raise:

    • :default - do not wait for current listener calls (if any) to finish, if the listener raises, it may result in unhandled error
    • :wait - wait for current listener calls (if any) to finish
    • :ignore_errors - do not wait for current listener calls (if any) to finish, all errors raised by the listeners after removal are silently caught

remove_all_listeners!(browser, event \\ nil, options \\ [])

@spec remove_all_listeners!(
  t(),
  event() | String.t() | nil,
  remove_all_listeners_options()
) :: :ok

Like remove_all_listeners/3, but returns the value and raises on error.

start_tracing(browser, page \\ nil, options \\ [])

@spec start_tracing(t(), Playwright.Page.t() | nil, start_tracing_options()) ::
  :ok | {:error, Playwright.error()}

Note

This API controls Chromium Tracing which is a low-level chromium-specific debugging tool. API to control Playwright Tracing could be found here.

You can use Playwright.Browser.start_tracing/3 and Playwright.Browser.stop_tracing/1 to create a trace file that can be opened in Chrome DevTools performance panel.

Usage

Browser.start_tracing!(browser, page, path: "trace.json")
Page.goto!(page, "https://www.google.com")
Browser.stop_tracing!(browser)

Since Playwright 1.11.

Arguments

  • page - Optional, if specified, tracing includes screenshots of the given page.

Options

The options may take the place of page, which is then nil.

  • :categories (list of String.t/0) - specify custom categories to use instead of default.
  • :path (String.t/0) - A path to write the trace file to.
  • :screenshots (boolean/0) - captures screenshots in the trace.

start_tracing!(browser, page \\ nil, options \\ [])

@spec start_tracing!(t(), Playwright.Page.t() | nil, start_tracing_options()) :: :ok

Like start_tracing/3, but returns the value and raises on error.

stop_tracing(browser)

@spec stop_tracing(t()) :: {:ok, binary()} | {:error, Playwright.error()}

Note

This API controls Chromium Tracing which is a low-level chromium-specific debugging tool. API to control Playwright Tracing could be found here.

Returns the buffer with trace data.

Since Playwright 1.11.

stop_tracing!(browser)

@spec stop_tracing!(t()) :: binary()

Like stop_tracing/1, but returns the value and raises on error.

unbind(browser)

@spec unbind(t()) :: :ok | {:error, Playwright.error()}

Unbinds the browser server previously bound with Playwright.Browser.bind/3.

Since Playwright 1.59.

unbind!(browser)

@spec unbind!(t()) :: :ok

Like unbind/1, but returns the value and raises on error.

version(browser)

@spec version(t()) :: String.t()

Returns the browser version.

Since Playwright 1.8.

Events

add_listener(browser, event, listener)

@spec add_listener(t(), :context, (Playwright.BrowserContext.t() -> term())) :: t()
@spec add_listener(t(), :disconnected, (t() -> term())) :: t()
@spec add_listener(t(), String.t(), (term() -> term())) :: t()

Adds an event listener for event, see the module docs for the events.

off(browser, event, listener)

@spec off(t(), :context, (Playwright.BrowserContext.t() -> term())) :: t()
@spec off(t(), :disconnected, (t() -> term())) :: t()
@spec off(t(), String.t(), (term() -> term())) :: t()

Removes an event listener added by on/3 or add_listener/3.

on(browser, event, listener)

@spec on(t(), :context, (Playwright.BrowserContext.t() -> term())) :: t()
@spec on(t(), :disconnected, (t() -> term())) :: t()
@spec on(t(), String.t(), (term() -> term())) :: t()

Adds an event listener for event, see the module docs for the events.

once(browser, event, listener)

@spec once(t(), :context, (Playwright.BrowserContext.t() -> term())) :: t()
@spec once(t(), :disconnected, (t() -> term())) :: t()
@spec once(t(), String.t(), (term() -> term())) :: t()

Adds an event listener that is removed after it is triggered once. See on/3.

prepend_listener(browser, event, listener)

@spec prepend_listener(t(), :context, (Playwright.BrowserContext.t() -> term())) ::
  t()
@spec prepend_listener(t(), :disconnected, (t() -> term())) :: t()
@spec prepend_listener(t(), String.t(), (term() -> term())) :: t()

Adds an event listener for event, see the module docs for the events.

remove_listener(browser, event, listener)

@spec remove_listener(t(), :context, (Playwright.BrowserContext.t() -> term())) :: t()
@spec remove_listener(t(), :disconnected, (t() -> term())) :: t()
@spec remove_listener(t(), String.t(), (term() -> term())) :: t()

Removes an event listener added by on/3 or add_listener/3.