Class: Ferrum::Browser

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/ferrum/browser.rb,
lib/ferrum/browser/xvfb.rb,
lib/ferrum/browser/binary.rb,
lib/ferrum/browser/command.rb,
lib/ferrum/browser/options.rb,
lib/ferrum/browser/process.rb,
lib/ferrum/browser/version_info.rb,
lib/ferrum/browser/options/chrome.rb,
lib/ferrum/browser/process/killer.rb,
lib/ferrum/browser/process/output.rb,
sig/ferrum/browser.rbs,
sig/ferrum/browser/xvfb.rbs,
sig/ferrum/browser/binary.rbs,
sig/ferrum/browser/command.rbs,
sig/ferrum/browser/options.rbs,
sig/ferrum/browser/process.rbs,
sig/ferrum/browser/version_info.rbs,
sig/ferrum/browser/options/chrome.rbs,
sig/ferrum/browser/process/killer.rbs,
sig/ferrum/browser/process/output.rbs

Overview

Note:

A Browser can host multiple Contexts (like incognito profiles) and multiple Pages within each of them, reachable through #contexts and #create_page.

The main entry point of the library. Instantiating it spawns (or connects to) a browser process and opens a CDP connection to it, exposing a single default Page that most of the top-level methods (go_to, at_css, screenshot, etc.) are delegated to for convenience.

Defined Under Namespace

Modules: Binary Classes: Command, Options, Process, VersionInfo, Xvfb

Constant Summary collapse

RESET_DEPRECATED =

Returns:

  • (String)
"browser.reset will be removed in Ferrum 1.0. Use browser.contexts.reset instead."

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ Browser

Initializes the browser.

Parameters:

  • options (Hash{Symbol => Object}, nil) (defaults to: nil) —

    Additional browser options.

  • (Hash[Symbol, untyped], nil)

Options Hash (options):

  • :headless (Boolean) — default: true —

    Set browser as headless or not.

  • :incognito (Boolean) — default: true —

    Create an incognito profile for the browser startup window.

  • :dockerize (Boolean) — default: false —

    Add CLI flags to a browser to run in a container.

  • :xvfb (Boolean) — default: false —

    Run browser in a virtual framebuffer.

  • :window_size ((Integer, Integer)) — default: [1024, 768] —

    The size of the browser window, [width, height]. It's the outer window, so the viewport is smaller by Chrome's toolbars, use Page::Viewport#resize for an exact viewport. With :xvfb it's the virtual screen size too. Only applies to a Chrome that Ferrum starts.

  • :init_scripts (Array<String, Hash>) —

    Paths to JS files or JS source code to run in every page and iframe before their own scripts, e.g. ["/path/to/script.js", { source: "window.secret = 'top'" }].

  • :extensions (Array<String, Hash>) —

    Deprecated, use :init_scripts.

  • :logger (#puts, Logger) —

    When present, debug output is written to this object, see Log.

  • :slowmo (Integer, Float) —

    Set a delay in seconds to wait before sending a command. Useful companion of a headless option, so that you have time to see changes.

  • :timeout (Numeric) — default: 5 —

    How long a call waits for the browser, in seconds: navigations, JS evaluation, DOM queries, dispatching input, etc. go_to, refresh and await_navigation wait for the page to load within it. A call that only sends commands waits for the browser's answer. A call that runs out raises TimeoutError. FERRUM_DEFAULT_TIMEOUT sets the default. Pass timeout: to go_to, refresh or await_navigation to change it for one call, or wrap calls in Deadline.within to bound them together.

  • :browser_path (String) —

    Path to Chrome binary, you can also set ENV variable as BROWSER_PATH=some/path/chrome bundle exec rspec.

  • :browser_options (Hash) —

    Additional command line options, see them all e.g. { "ignore-certificate-errors" => nil }

  • :ignore_default_browser_options (Boolean) —

    Ferrum has a number of default options it passes to the browser, if you set this to true then only options you put in :browser_options will be passed to the browser, except required ones of course.

  • :port (Integer) —

    Remote debugging port for headless Chrome.

  • :host (String) —

    Remote debugging address for headless Chrome.

  • :url (String) —

    URL for a running instance of Chrome. If this is set, a browser process will not be spawned.

  • :process_timeout (Integer) —

    How long to wait for the Chrome process to respond on startup, or to connect to the browser at :url or :ws_url.

  • :ws_max_receive_size (Integer) —

    How big messages to accept from Chrome over the web socket, in bytes. Defaults to 64MB. Incoming messages larger this will cause a DeadBrowserError.

  • :ssl_context (OpenSSL::SSL::SSLContext) —

    TLS settings for connecting to the browser at an https :url or a wss :ws_url. By default the certificate and the host name are verified against the system's trusted certificates. Pass a context that trusts your own certificate, or one with verify_mode OpenSSL::SSL::VERIFY_NONE to skip verification.

  • :proxy (Hash) —

    Specify proxy settings, read more.

  • :save_path (String) —

    Path to save attachments with Content-Disposition header.

  • :env (Hash) —

    Environment variables you'd like to pass through to the process.



150
151
152
153
154
155
# File 'lib/ferrum/browser.rb', line 150

def initialize(options = nil)
  @options = Options.new(options)
  @client = @process = @contexts = nil

  start
end

Instance Attribute Details

#client ⇒ ::Ferrum::Client (readonly)

Returns the value of attribute client.

Returns:



50
51
52
# File 'lib/ferrum/browser.rb', line 50

def client
  @client
end

#contexts ⇒ Contexts (readonly)

Returns the value of attribute contexts.

Returns:



50
51
52
# File 'lib/ferrum/browser.rb', line 50

def contexts
  @contexts
end

#options ⇒ Browser::Options (readonly)

Returns the value of attribute options.

Returns:



50
51
52
# File 'lib/ferrum/browser.rb', line 50

def options
  @options
end

#process ⇒ Browser::Process (readonly)

Returns the value of attribute process.

Returns:



50
51
52
# File 'lib/ferrum/browser.rb', line 50

def process
  @process
end

Instance Method Details

#add_init_script ⇒ ::Array[String]

Parameters:

  • script (String, Hash[Symbol, String])

Returns:

  • (::Array[String])


36
# File 'sig/ferrum/browser.rbs', line 36

def add_init_script: (String | Hash[Symbol, String] script) -> ::Array[String]

#base_url ⇒ String?

Returns:

  • (String, nil)


19
# File 'sig/ferrum/browser.rbs', line 19

def base_url: () -> String?

#base_url= ⇒ String

Parameters:

  • (String)

Returns:

  • (String)


21
# File 'sig/ferrum/browser.rbs', line 21

def base_url=: (String) -> String

#close ⇒ nil

Shuts the browser down gracefully with the CDP Browser.close command, a remote browser included. Only the browser exits: the connection and a launched process are still to be cleaned up, with #disconnect and browser.process.stop, or with #quit.

Returns:

  • (nil)


319
320
321
322
# File 'lib/ferrum/browser.rb', line 319

def close
  command("Browser.close")
  nil
end

#command(method, timeout: nil, **params) ⇒ Hash

Sends a CDP command to the browser itself, not to the default page like most other Browser methods, #on included. Use page.command for page domains such as Page, Runtime or DOM.

Parameters:

  • method (String) —

    The CDP method name, e.g. "Browser.getVersion".

  • timeout (Numeric, Deadline, nil) (defaults to: nil) —

    How long to wait for the response, the browser's timeout by default.

  • params (Hash) —

    The command's parameters.

  • timeout: (::Numeric, Deadline, nil) (defaults to: nil)

Returns:

  • (Hash) —

    The command's result.

Raises:



343
344
345
# File 'lib/ferrum/browser.rb', line 343

def command(method, timeout: nil, **params)
  client.command(method, timeout: timeout || self.timeout, **params)
end

#crash ⇒ Hash[String, untyped]

Crashes browser.

Returns:

  • (Hash[String, untyped])


307
308
309
# File 'lib/ferrum/browser.rb', line 307

def crash
  command("Browser.crash")
end

#create_page(new_context:, new_window:, proxy:) ⇒ Page #create_page(new_context:, new_window:, proxy:) ⇒ T

Creates a new page.

Overloads:

  • #create_page(new_context:, new_window:, proxy:) ⇒ Page

    Parameters:

    • new_context: (Boolean)
    • new_window: (Boolean)
    • proxy: (Hash[Symbol, (String | ::Integer)], nil)

    Returns:

  • #create_page(new_context:, new_window:, proxy:) ⇒ T

    Parameters:

    • new_context: (Boolean)
    • new_window: (Boolean)
    • proxy: (Hash[Symbol, (String | ::Integer)], nil)

    Returns:

    • (T)

Parameters:

  • new_context (Boolean) (defaults to: false) —

    Whether to create a page in a new context or not.

  • new_window (Boolean) (defaults to: false) —

    Whether to open the page in a window of its own instead of a tab.

  • proxy (Hash) (defaults to: nil) —

    Whether to use proxy for a page. The page will be created in a new context if so.

Yields:

Yield Parameters:

Yield Returns:

  • (T)

Returns:

Raises:



174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/ferrum/browser.rb', line 174

def create_page(new_context: false, new_window: false, proxy: nil)
  page = if new_context || proxy
           params = {}

           if proxy
             options.validate_proxy(proxy)
             params.merge!(proxyServer: "#{proxy[:host]}:#{proxy[:port]}")
             params.merge!(proxyBypassList: proxy[:bypass]) if proxy[:bypass]
           end

           context = contexts.create(**params)
           context.create_page(new_window: new_window, proxy: proxy)
         else
           default_context.create_page(new_window: new_window)
         end

  block_given? ? yield(page) : page
ensure
  if block_given?
    page&.close
    context&.dispose if new_context
  end
end

#debug(bind = nil) ⇒ void

This method returns an undefined value.

Opens headless session in the browser devtools frontend.

Parameters:

  • bind (Binding, nil) (defaults to: nil)

Since:

  • 0.16



367
368
369
370
371
372
373
374
375
376
# File 'lib/ferrum/browser.rb', line 367

def debug(bind = nil)
  ::Process.spawn(process.path, debug_url)

  bind ||= binding
  if bind.respond_to?(:pry)
    Pry.start(bind)
  else
    bind.irb
  end
end

#default_user_agent ⇒ String?

Returns:

  • (String, nil)


27
# File 'sig/ferrum/browser.rbs', line 27

def default_user_agent: () -> String?

#default_user_agent= ⇒ String

Parameters:

  • (String)

Returns:

  • (String)


29
# File 'sig/ferrum/browser.rbs', line 29

def default_user_agent=: (String) -> String

#disconnect ⇒ nil

Closes the client connection, leaving the browser running, whether Ferrum launched it or connected to it. A launched browser stays reachable through #process, so it can be stopped later with browser.process.stop or #quit.

Examples:

Shut a launched browser down gracefully

browser.close
browser.disconnect
browser.process.stop

Returns:

  • (nil)


293
294
295
296
297
298
299
300
301
302
# File 'lib/ferrum/browser.rb', line 293

def disconnect
  return unless @client

  begin
    @client.close
  ensure
    @client = @contexts = nil
  end
  nil
end

#init_scripts ⇒ ::Array[String]

Returns:

  • (::Array[String])


34
# File 'sig/ferrum/browser.rbs', line 34

def init_scripts: () -> ::Array[String]

#quit(wait: true) ⇒ Thread?

Closes the client connection and terminates the browser process Ferrum launched. A remote browser, connected to with :url or :ws_url, is only disconnected from and keeps running; see #close to shut it down. Also stops a browser left running by #disconnect.

Parameters:

  • wait (Boolean) (defaults to: true) —

    Whether to block until the process is confirmed dead and its user data directory removed (the default), or return immediately and run that cleanup on a background thread instead. See Ferrum::Browser::Process#stop.

  • wait: (Boolean) (defaults to: true)

Returns:

  • (Thread, nil) —

    The background cleanup thread when wait: false, nil otherwise.



235
236
237
238
239
240
241
242
243
244
245
# File 'lib/ferrum/browser.rb', line 235

def quit(wait: true)
  return if @client.nil? && @process.nil?

  begin
    disconnect
  ensure
    thread = @process&.stop(wait: wait)
    @process = nil
  end
  thread
end

#reset ⇒ nil

Deprecated.

Use Contexts#reset via browser.contexts.reset.

Closes browser tabs opened by the Browser instance.

Returns:

  • (nil)

Raises:



207
208
209
210
211
# File 'lib/ferrum/browser.rb', line 207

def reset
  Utils::Deprecate.warn(RESET_DEPRECATED, user_code: true)
  contexts.reset
  nil
end

#restart ⇒ void

This method returns an undefined value.

Restarts the browser process, keeping the same options.



216
217
218
219
# File 'lib/ferrum/browser.rb', line 216

def restart
  quit
  start
end

#shutdown(wait: true) ⇒ Thread?

Shuts the browser down for good: asks it to exit with #close, closes the connection and, for a browser Ferrum launched, lets the process exit on its own before killing it and removing its user data directory. Unlike #quit, it also shuts down a remote browser, connected to with :url or :ws_url.

Parameters:

  • wait (Boolean) (defaults to: true) —

    Whether to block until the process is confirmed dead and its user data directory removed (the default), or return immediately and run that cleanup on a background thread instead. See Ferrum::Browser::Process#stop.

  • wait: (Boolean) (defaults to: true)

Returns:

  • (Thread, nil) —

    The background cleanup thread when wait: false, nil otherwise.

Raises:

  • (TimeoutError) —

    When the browser doesn't answer Browser.close, e.g. it hangs. A launched browser is killed before the error is raised, a remote one is left as it is.



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/ferrum/browser.rb', line 264

def shutdown(wait: true)
  return if @client.nil? && @process.nil?

  begin
    close_browser if @client
  ensure
    begin
      disconnect
    ensure
      thread = @process&.stop(wait: wait, grace: Process::Killer::KILL_TIMEOUT)
      @process = nil
    end
  end
  thread
end

#timeout ⇒ ::Numeric

Returns:

  • (::Numeric)


23
# File 'sig/ferrum/browser.rbs', line 23

def timeout: () -> ::Numeric

#timeout= ⇒ ::Numeric

Parameters:

  • (::Numeric)

Returns:

  • (::Numeric)


25
# File 'sig/ferrum/browser.rbs', line 25

def timeout=: (::Numeric) -> ::Numeric

#version ⇒ VersionInfo

Gets the version information from the browser.

Returns:

Raises:

Since:

  • 0.13



356
357
358
# File 'lib/ferrum/browser.rb', line 356

def version
  VersionInfo.new(command("Browser.getVersion"))
end