Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,16 @@
### Changed
- `User-Agent` and `Accept-Language` set through `headers` are only sent with requests, they no longer change what
`navigator` reports. Use `network.emulate(user_agent:, accept_language:)` to override both
- An unknown mouse button, `cookies.remove` without `:domain` or `:url`, a relative `go_to` without `:base_url` and a
relative `:save_path` raise `ArgumentError` instead of `RuntimeError` or `Ferrum::Error`. A failed screencast and
`debug_url` raise `Ferrum::Error`. Errors that had no message or a misleading one say what's missing now [#557]

### Deprecated

### Fixed

### Removed
- `Browser::Options::BASE_URL_SCHEMA`, use `BASE_URL_SCHEMES`
- `target.window?` and `windows` of a context and of the browser, use `target.opener_id`, `await_page { ... }` or
`pages(&:opener_id)`
- `:js_errors`, uncaught exceptions are in `page.console` with `source: :exception`, and `page.on(:console)` yields them
Expand Down
4 changes: 2 additions & 2 deletions lib/ferrum/browser.rb
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ class Browser
# {Ferrum::DeadBrowserError}.
#
# @option options [Hash] :proxy
# Specify proxy settings, [read more](https://github.com/rubycdp/ferrum#proxy).
# Specify proxy settings, [read more](https://docs.rubycdp.com/docs/ferrum/proxy).
#
# @option options [String] :save_path
# Path to save attachments with [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition)
Expand Down Expand Up @@ -331,7 +331,7 @@ def debug_url
response = JSON.parse(Net::HTTP.get(URI(build_remote_debug_url(path: "/json"))))

devtools_frontend_path = response[0]&.[]("devtoolsFrontendUrl")
raise "Could not generate debug url for remote debugging session" unless devtools_frontend_path
raise Error, "Could not generate debug url for remote debugging session" unless devtools_frontend_path

build_remote_debug_url(path: devtools_frontend_path)
end
Expand Down
6 changes: 3 additions & 3 deletions lib/ferrum/browser/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ class Options
BROWSER_PORT = "0"
BROWSER_HOST = "127.0.0.1"
WINDOW_SIZE = [1024, 768].freeze
BASE_URL_SCHEMA = %w[http https].freeze
BASE_URL_SCHEMES = %w[http https].freeze
DEFAULT_TIMEOUT = ENV.fetch("FERRUM_DEFAULT_TIMEOUT", 5).to_f
PROCESS_TIMEOUT = ENV.fetch("FERRUM_PROCESS_TIMEOUT", 10).to_i

Expand Down Expand Up @@ -140,8 +140,8 @@ def parse_logger(logger)

def parse_base_url(value)
parsed = Addressable::URI.parse(value)
unless BASE_URL_SCHEMA.include?(parsed&.normalized_scheme)
raise ArgumentError, "`base_url` should be absolute and include schema: #{BASE_URL_SCHEMA.join(' | ')}"
unless BASE_URL_SCHEMES.include?(parsed&.normalized_scheme)
raise ArgumentError, "`base_url` should be absolute and include scheme: #{BASE_URL_SCHEMES.join(' | ')}"
end

parsed
Expand Down
15 changes: 11 additions & 4 deletions lib/ferrum/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def send_message(message, timeout:)
raise TimeoutError.new(message[:method], session_id: message[:sessionId]) unless data

error, response = data.values_at("error", "result")
raise_browser_error(error) if error
raise_browser_error(error, message) if error
response
end

Expand Down Expand Up @@ -413,7 +413,7 @@ def next_command_id
@command_id_mutex.synchronize { @command_id += 1 }
end

def raise_browser_error(error)
def raise_browser_error(error, message)
case error["message"]
# Node has disappeared while we were trying to get it
when "No node with given id found",
Expand All @@ -425,12 +425,19 @@ def raise_browser_error(error)
when "Cannot find context with specified id"
raise NoExecutionContextError, error
when "No target with given id found"
raise NoSuchPageError
raise NoSuchPageError, no_target_message(message)
when /Could not compute content quads/
raise CoordinatesNotFoundError
raise CoordinatesNotFoundError, error["message"]
else
raise BrowserError, error
end
end

def no_target_message(message)
target_id = message.dig(:params, :targetId)
return "#{message[:method]} found no target, it's closed or never existed" unless target_id

"#{message[:method]} found no target #{target_id}, it's closed or never existed"
end
end
end
2 changes: 1 addition & 1 deletion lib/ferrum/context.rb
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def delete_target(target_id)
# @raise [TimeoutError]
def attach_target(target_id)
target = @targets[target_id]
raise NoSuchTargetError unless target
raise NoSuchTargetError, "No target #{target_id} in context #{id}" unless target
return target if target.session_id

@contexts.manually_attached(target_id)
Expand Down
4 changes: 3 additions & 1 deletion lib/ferrum/cookies.rb
Original file line number Diff line number Diff line change
Expand Up @@ -118,14 +118,16 @@ def set(options)
#
# @return [nil]
#
# @raise [ArgumentError] if neither `:domain`, `:url` nor `:base_url` is set.
#
# @raise [TimeoutError]
#
# @example
# browser.cookies.remove(name: "stealth", domain: "google.com") # => true
#
def remove(name:, **options)
domain = options[:domain] || (default_domain unless options[:url])
raise "Specify :domain or :url option" if !domain && !options[:url]
raise ArgumentError, "Specify :domain or :url option" if !domain && !options[:url]

uri = URI.parse(options[:url]) if options[:url]
cookies = select do |cookie|
Expand Down
9 changes: 5 additions & 4 deletions lib/ferrum/downloads.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,15 @@ def await_download!(timeout: WAIT_TIMEOUT, &)
#
# @return [nil]
#
# @raise [ArgumentError]
# @raise [Ferrum::Error]
# @raise [ArgumentError] if the behavior is unknown or the path isn't absolute.
#
# @raise [TimeoutError]
#
def set_behavior(save_path:, behavior: :allow)
raise ArgumentError unless VALID_BEHAVIOR.include?(behavior.to_sym)
raise Error, "supply absolute path for `:save_path` option" unless Pathname.new(save_path.to_s).absolute?
unless VALID_BEHAVIOR.include?(behavior.to_sym)
raise ArgumentError, "Unknown behavior #{behavior.inspect}, use #{VALID_BEHAVIOR.map(&:inspect).join(' | ')}"
end
raise ArgumentError, "Supply absolute path for `:save_path` option" unless Pathname.new(save_path.to_s).absolute?

options = { browserContextId: @page.context_id } if @page.context_id
@page.command("Browser.setDownloadBehavior",
Expand Down
29 changes: 15 additions & 14 deletions lib/ferrum/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@ class NoSuchTargetError < Error; end
class NoSuchPageError < NoSuchTargetError; end
# Raised when no browser binary can be found at the configured path.
class BinaryNotFoundError < Error; end

# Raised when a required file path option is empty.
class EmptyPathError < Error; end
class EmptyPathError < Error
def initialize(message = "PATH is empty, there's nowhere to look for the executable")
super
end
end

# Raised when a request fails to reach the server, e.g. due to DNS or
# connectivity issues.
Expand Down Expand Up @@ -52,10 +57,7 @@ def initialize(command = nil, session_id: nil)
# @return [String]
#
def message
"Timed out waiting for #{awaited}. It's possible that this happened " \
"because something took a very long time (for example a page load " \
"was slow). If so, setting the :timeout option to a higher value might " \
"help."
"Timed out waiting for #{awaited}, set the :timeout option higher if it's expected to be slow"
end

private
Expand Down Expand Up @@ -167,7 +169,8 @@ class ProcessTimeoutError < Error

def initialize(timeout, output)
@output = output
super("Browser did not produce websocket url within #{timeout} seconds, try to increase `:process_timeout`. See https://github.com/rubycdp/ferrum#customization")
super("Browser did not produce websocket url within #{timeout} seconds, try to increase `:process_timeout`. " \
"See https://docs.rubycdp.com/docs/ferrum/customization")
end
end

Expand All @@ -185,16 +188,16 @@ def initialize(url, status = nil)
end
end

# Raised when trying to interact with a browser process that has died or
# a window that has already been closed.
# Raised when the connection to the browser is lost, because the browser
# crashed, was closed, or the websocket dropped.
class DeadBrowserError < Error
def initialize(message = "Browser is dead or given window is closed")
def initialize(message = "Lost the connection to the browser, it crashed or was closed")
super
end
end

# Raised when a node keeps moving between attempts to interact with it,
# e.g. while trying to click it.
# e.g. while trying to click or hover it.
class NodeMovingError < Error
def initialize(node, prev, current)
@node = node
Expand All @@ -209,9 +212,7 @@ def initialize(node, prev, current)
# @return [String]
#
def message
"#{@node.inspect} that you're trying to click is moving, hence " \
"we cannot. Previously it was at #{@prev.inspect} but now at " \
"#{@current.inspect}."
"#{@node.inspect} keeps moving, it was at #{@prev.inspect} and then at #{@current.inspect}"
end
end

Expand Down Expand Up @@ -276,7 +277,7 @@ class NodeNotFoundError < BrowserError; end
# command against, e.g. because the frame isn't attached.
class NoExecutionContextError < BrowserError
def initialize(response = nil)
super(response || { "message" => "There's no context available" })
super(response || { "message" => "There's no JavaScript context to run in, the frame is detached or navigating" })
end
end

Expand Down
4 changes: 3 additions & 1 deletion lib/ferrum/frame.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,9 @@ def initialize(id, page, parent_id = nil)
#
# @api private
def state=(value)
raise ArgumentError unless STATE_VALUES.include?(value)
unless STATE_VALUES.include?(value)
raise ArgumentError, "Unknown frame state #{value.inspect}, use #{STATE_VALUES.map(&:inspect).join(' | ')}"
end

@state = value
end
Expand Down
10 changes: 5 additions & 5 deletions lib/ferrum/keyboard.rb
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,9 @@ def type(*keys, timeout: nil)
# end
#
def hold(*keys)
raise ArgumentError, "block is required" unless block_given?
raise ArgumentError, "Block is required" unless block_given?

keys = keys.map { |key| modifier_name(key) || raise(ArgumentError, "not a modifier key: #{key.inspect}") }
keys = keys.map { |key| modifier_name(key) || raise(ArgumentError, "Not a modifier key: #{key.inspect}") }
previous = @held_modifiers
pressed = []

Expand Down Expand Up @@ -212,7 +212,7 @@ def dispatch_modifier(type, name)
def normalize_keys(keys, pressed_keys = [], memo = [])
case keys
when Array
raise ArgumentError, "empty keys passed" if keys.empty?
raise ArgumentError, "Empty keys passed" if keys.empty?

pressed_keys.push([])
memo += combine_strings(keys).map do |key|
Expand All @@ -232,7 +232,7 @@ def normalize_keys(keys, pressed_keys = [], memo = [])
to_options(key)
end
when String
raise ArgumentError, "empty keys passed" if keys.empty?
raise ArgumentError, "Empty keys passed" if keys.empty?

pressed = pressed_keys.flatten
mask = pressed.map { |k| MODIFIERS[k] }.reduce(@held_modifiers, :|)
Expand Down Expand Up @@ -263,7 +263,7 @@ def normalize_keys(keys, pressed_keys = [], memo = [])
end.flatten
end
else
raise ArgumentError, "unexpected argument"
raise ArgumentError, "Keys should be a String, Symbol or Array, got #{keys.inspect}"
end
end
# rubocop:enable Metrics/PerceivedComplexity
Expand Down
8 changes: 7 additions & 1 deletion lib/ferrum/mouse.rb
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ def scroll_to(x: nil, y: nil)
#
# @return [self]
#
# @raise [ArgumentError] if the button is unknown.
#
# @raise [TimeoutError]
#
def click(x:, y:, delay: 0, navigation_wait: Page::NAVIGATION_WAIT, timeout: nil, **options)
Expand Down Expand Up @@ -137,6 +139,8 @@ def click(x:, y:, delay: 0, navigation_wait: Page::NAVIGATION_WAIT, timeout: nil
#
# @return [self]
#
# @raise [ArgumentError] if the button is unknown.
#
# @raise [TimeoutError]
#
def down(**options)
Expand Down Expand Up @@ -167,6 +171,8 @@ def down(**options)
#
# @return [self]
#
# @raise [ArgumentError] if the button is unknown.
#
# @raise [TimeoutError]
#
def up(**options)
Expand Down Expand Up @@ -251,7 +257,7 @@ def modifiers_mask(modifiers)

def validate_button(button)
button = button.to_s
raise "Invalid button: #{button}" unless BUTTON_MASKS.key?(button)
raise ArgumentError, "Invalid button: #{button}" unless BUTTON_MASKS.key?(button)

button
end
Expand Down
4 changes: 2 additions & 2 deletions lib/ferrum/network.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class Network
SignedExchange Ping CSPViolationReport Preflight Other].freeze
AUTHORIZE_BLOCK_MISSING = "Block is missing, call `authorize(...) { |r| r.continue } " \
"or subscribe to `on(:request)` events before calling it"
AUTHORIZE_TYPE_WRONG = ":type should be in #{AUTHORIZE_TYPE}".freeze
AUTHORIZE_TYPE_WRONG = ":type should be #{AUTHORIZE_TYPE.map(&:inspect).join(' | ')}".freeze
ALLOWED_CONNECTION_TYPE = %w[none cellular2g cellular3g cellular4g bluetooth ethernet wifi wimax other].freeze

# Network traffic.
Expand Down Expand Up @@ -194,7 +194,7 @@ def status
# traffic.size # => 0
#
def clear(type)
raise ArgumentError, ":type should be in #{CLEAR_TYPE}" unless CLEAR_TYPE.include?(type)
raise ArgumentError, ":type should be #{CLEAR_TYPE.map(&:inspect).join(' | ')}" unless CLEAR_TYPE.include?(type)

if type == :traffic
@traffic.clear
Expand Down
4 changes: 2 additions & 2 deletions lib/ferrum/node.rb
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,13 @@ def node_id
@node_id = begin
id = page.command("DOM.pushNodesByBackendIdsToFrontend",
backendNodeIds: [backend_node_id])["nodeIds"].first
raise NodeNotFoundError, { "message" => "node is not trackable" } if id.zero?
raise NodeNotFoundError, { "message" => "Node is not trackable" } if id.zero?

id
rescue BrowserError => e
raise unless e.message == "Document needs to be requested first"

raise NodeNotFoundError, { "message" => "node is not trackable, the page is still loading a new document" }
raise NodeNotFoundError, { "message" => "Node is not trackable, the page is still loading a new document" }
end
@document_version = document_version
@node_id
Expand Down
2 changes: 1 addition & 1 deletion lib/ferrum/page.rb
Original file line number Diff line number Diff line change
Expand Up @@ -587,7 +587,7 @@ def build_chain(name)

def accept_dialog(dialog)
warn "Dialog was shown but no `on(:dialog)` callback handled it, accepting it by default. " \
"Please take a look at https://github.com/rubycdp/ferrum#dialogs"
"Please take a look at https://docs.rubycdp.com/docs/ferrum/dialogs"
dialog.accept
end

Expand Down
4 changes: 3 additions & 1 deletion lib/ferrum/page/cookies.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,13 +87,15 @@ def set(options)
#
# @return [nil]
#
# @raise [ArgumentError] if neither `:domain`, `:url` nor `:base_url` is set.
#
# @raise [TimeoutError]
#
# @example
# page.cookies.remove(name: "stealth") # => true
#
def remove(name:, **options)
raise "Specify :domain or :url option" if !options[:domain] && !options[:url] && !default_domain
raise ArgumentError, "Specify :domain or :url option" if !options[:domain] && !options[:url] && !default_domain

options = options.merge(name: name)
options[:domain] ||= default_domain unless options[:url]
Expand Down
7 changes: 6 additions & 1 deletion lib/ferrum/page/navigation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ module Navigation
# @return [String, nil]
# The navigated frame's id, or `nil` when the page doesn't load in time.
#
# @raise [ArgumentError] if the URL is relative and there's no `:base_url`.
#
# @raise [StatusError]
# If the request fails.
#
Expand Down Expand Up @@ -58,6 +60,8 @@ def go_to(url = nil, timeout: nil, referrer: nil)
# @return [String]
# The navigated frame's id.
#
# @raise [ArgumentError] if the URL is relative and there's no `:base_url`.
#
# @raise [StatusError]
# If the request fails.
#
Expand Down Expand Up @@ -299,7 +303,8 @@ def combine_url!(url_or_path)
nil_or_relative = url.nil? || url.relative?

if nil_or_relative && [email protected]_url
raise "Set :base_url browser's option or use absolute url in `go_to`, you passed: #{url_or_path}"
raise ArgumentError,
"Set :base_url browser's option or use absolute url in `go_to`, you passed: #{url_or_path}"
end

(nil_or_relative ? @options.base_url.join(url.to_s) : url).to_s
Expand Down
Loading
Loading