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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,18 @@
element under it, unlike `scroll_by` [#744]
- `RemoteObject#evaluate`, `#evaluate_handle` and `#execute` run JavaScript with `this` bound to the handle, as on
`Node` [#746]
- `Network::Response#from_disk_cache?` and `#from_service_worker?` tell whether a response came from the disk cache or
a service worker [#751]
- `browser.disconnect` closes the connection and leaves the browser running, so `close`, `disconnect` and
`process.stop` make up a custom shutdown. `quit` still stops a browser disconnected this way [#750]
- `browser.shutdown` asks the browser to exit, lets a launched one do so before killing it, and also shuts down a
remote browser, unlike `quit`. `process.stop(grace:)` waits that long before signaling [#750]

### Changed
- `downloads.files` and `await_download` return `Ferrum::Download` objects instead of event hashes, with `path`
where Chrome saved the file, `state`, `completed?`, `suggested_filename` and `to_h` for the raw params [#751]
- `window_bounds` returns the shape `window_bounds=` takes, symbol keys and `window_state:`, instead of CDP's string
keys and `"windowState"` [#751]
- A `wss://` connection to the browser verifies its certificate and host name and sends SNI, as the `https`
`/json/version` request already did. A self-signed browser needs `:ssl_context`, see the option [#742]
- `User-Agent` and `Accept-Language` set through `headers` are only sent with requests, they no longer change what
Expand Down
7 changes: 7 additions & 0 deletions docs/21-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ target = browser.service_workers.first # => #<Ferrum::Target @id="..." @type="se
target.connected? # => false
```

A response the service worker answered, instead of the network, reports `from_service_worker?`:

```ruby
page.evaluate(%(await (await fetch("/cached")).text()))
page.network.response.from_service_worker? # => true
```

#### attach_target(target_id) : `Boolean`

Manually attaches to a target discovered via `service_workers`. Once attached, `target.worker` returns a connected
Expand Down
4 changes: 2 additions & 2 deletions docs/3-navigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,12 @@ Set window bounds
browser.window_bounds = { left: 10, top: 20, width: 1024, height: 768, window_state: "normal" }
```

#### window_bounds : `Hash<String, Integer | String>`
#### window_bounds : `Hash<Symbol, Integer | String>`

Get window bounds

```ruby
browser.window_bounds # => { "left": 0, "top": 1286, "width": 10, "height": 10, "windowState": "normal" }
browser.window_bounds # => { left: 0, top: 1286, width: 10, height: 10, window_state: "normal" }
```

#### window_id : `Integer`
Expand Down
5 changes: 4 additions & 1 deletion docs/7-network.md
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,11 @@ Once every option is back to `nil` the override is removed and Chrome sends its

#### cache=(enabled)

Turns the browser cache on or off for the page's requests.
Turns the browser cache on or off for the page's requests. `response.from_disk_cache?` tells whether a response came
from the cache:

```ruby
page.network.cache = false
page.go_to("https://github.com/")
page.network.response.from_disk_cache? # => false
```
28 changes: 20 additions & 8 deletions docs/8-downloads.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,39 @@ sidebar_position: 8

`page.downloads`

#### files `Array<Hash>`
#### files `Array<Ferrum::Download>`

Returns all information about downloaded files as a `Hash`.
Every download the page started, finished or not.

```ruby
page.go_to("http://localhost/attachment.pdf")
page.downloads.files # => [{"frameId"=>"E3316DF1B5383D38F8ADF7485005FDE3", "guid"=>"11a68745-98ac-4d54-9b57-9f9016c268b3", "url"=>"http://localhost/attachment.pdf", "suggestedFilename"=>"attachment.pdf", "totalBytes"=>4911, "receivedBytes"=>4911, "state"=>"completed"}]
page.downloads.files # => [#<Ferrum::Download @guid="11a68745-..." @suggested_filename="attachment.pdf" @state=:completed>]
```

#### await_download(timeout: 5) { } : `Hash` | `nil`
#### await_download(timeout: 5) { } : `Ferrum::Download` | `nil`

Runs the block and waits for the download it starts to finish. Returns the download, like an entry of `files`, its
`"state"` is `"completed"` or `"canceled"`. Returns `nil` if it doesn't finish within `timeout`, 5 seconds by
default. `await_download!` raises `Ferrum::TimeoutError` instead. Also on `page`.
Runs the block and waits for the download it starts to finish, `completed?` or `canceled?`. Returns `nil` if it
doesn't finish within `timeout`, 5 seconds by default. `await_download!` raises `Ferrum::TimeoutError` instead. Also on
`page`.

```ruby
page.go_to("http://localhost/page")
page.await_download { page.at_css("#download").click } # => {"suggestedFilename"=>"attachment.pdf", "state"=>"completed", ...}
download = page.await_download { page.at_css("#download").click }
download.path # => "/tmp/attachment.pdf"
page.await_download! { page.go_to("http://localhost/attachment.pdf") }
```

#### Ferrum::Download

* `guid` `String` the download's id
* `url` `String` where the file is downloaded from
* `suggested_filename` `String` the name the server or the link suggested
* `frame_id` `String` the frame that started the download
* `path` `String | nil` where Chrome saved the file once it's completed, named after `guid` with `behavior: :allowAndName`
* `state` `Symbol | nil` `:in_progress`, `:completed` or `:canceled`, with `completed?` and `canceled?`
* `received_bytes`, `total_bytes` `Integer | nil`
* `to_h` `Hash` the raw CDP event params

#### set_behavior(\*\*options)

Sets behavior in case of file to be downloaded.
Expand Down
139 changes: 139 additions & 0 deletions lib/ferrum/download.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
# frozen_string_literal: true

module Ferrum
#
# A file the page downloads, built from Chrome's `Browser.downloadWillBegin`
# event and updated by every `Browser.downloadProgress` after it.
#
class Download
STATES = { "inProgress" => :in_progress, "completed" => :completed, "canceled" => :canceled }.freeze

#
# @param [Hash{String => Object}] params
# The `Browser.downloadWillBegin` event params.
#
# @api private
#
def initialize(params)
@params = params
end

#
# The download's id, unique for the browser.
#
# @return [String]
#
def guid
@params["guid"]
end

#
# The URL the file is downloaded from.
#
# @return [String]
#
def url
@params["url"]
end

#
# The file name the server or the link suggested.
#
# @return [String]
#
def suggested_filename
@params["suggestedFilename"]
end

#
# The id of the frame that started the download.
#
# @return [String]
#
def frame_id
@params["frameId"]
end

#
# Where the file was saved, as Chrome reports it once the download is
# completed. With `behavior: :allowAndName` it's named after {#guid}.
#
# @return [String, nil]
#
# @example
# page.await_download { page.at_css("#download").click }.path # => "/tmp/downloads/file.pdf"
#
def path
@params["filePath"]
end

#
# @return [:in_progress, :completed, :canceled, nil]
# `nil` until Chrome reports progress.
#
def state
STATES[@params["state"]]
end

#
# @return [Boolean]
#
def completed?
state == :completed
end

#
# @return [Boolean]
#
def canceled?
state == :canceled
end

#
# Bytes received so far.
#
# @return [Integer, nil]
#
def received_bytes
@params["receivedBytes"]
end

#
# The file size, `0` when the server doesn't send one.
#
# @return [Integer, nil]
#
def total_bytes
@params["totalBytes"]
end

#
# The raw event params, merged from all events of this download.
#
# @return [Hash{String => Object}]
#
def to_h
@params.dup
end

#
# Merges a `Browser.downloadProgress` event into the download.
#
# @param [Hash{String => Object}] params
#
# @return [void]
#
# @api private
#
def update(params)
@params = @params.merge(params)
end

#
# @return [String]
#
def inspect
"#<#{self.class} @guid=#{guid.inspect} @suggested_filename=#{suggested_filename.inspect} @state=#{state.inspect}>"
end
end
end
20 changes: 11 additions & 9 deletions lib/ferrum/downloads.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
# frozen_string_literal: true

require "ferrum/download"

module Ferrum
#
# Tracks files downloaded by a page. Configures the browser's download
Expand All @@ -21,9 +23,9 @@ def initialize(page)
end

#
# Returns information about all downloaded files.
# Every download the page started, finished or not.
#
# @return [Array<Hash>]
# @return [Array<Download>]
#
def files
@files.values
Expand All @@ -37,15 +39,15 @@ def files
#
# @yield The code that starts the download, e.g. clicking a link.
#
# @return [Hash, nil]
# The finished download, like an entry of {#files}, its `"state"` is
# `"completed"` or `"canceled"`. `nil` if it doesn't finish in time.
# @return [Download, nil]
# The finished download, {Download#completed?} or {Download#canceled?}.
# `nil` if it doesn't finish in time.
#
# @raise [ArgumentError]
# If no block is given.
#
# @example
# page.await_download { page.at_css("#download").click } # => {"suggestedFilename" => "file.pdf", ...}
# page.await_download { page.at_css("#download").click }.path # => "/tmp/downloads/file.pdf"
#
def await_download(timeout: WAIT_TIMEOUT)
raise ArgumentError, "await_download needs a block that starts the download" unless block_given?
Expand All @@ -66,7 +68,7 @@ def await_download(timeout: WAIT_TIMEOUT)
#
# @yield The code that starts the download.
#
# @return [Hash]
# @return [Download]
#
# @raise [TimeoutError]
# If the download doesn't finish in time.
Expand Down Expand Up @@ -128,7 +130,7 @@ def subscribe
def subscribe_download_will_begin
@page.on("Browser.downloadWillBegin") do |params|
@idle.clear
@files[params["guid"]] = params
@files[params["guid"]] = Download.new(params)
@waiters_mutex.synchronize { @waiters.find { |w| w[:guid].nil? }&.store(:guid, params["guid"]) }
end
end
Expand All @@ -141,7 +143,7 @@ def subscribe_download_will_begin
# @api private
def subscribe_download_progress
@page.on("Browser.downloadProgress") do |params|
@files[params["guid"]].merge!(params)
@files[params["guid"]].update(params)

case params["state"]
when "completed", "canceled"
Expand Down
18 changes: 18 additions & 0 deletions lib/ferrum/network/response.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,24 @@ def content_type
@content_type ||= headers.find { |k, _| k.downcase == "content-type" }&.last&.sub(/;.*\z/, "")
end

#
# Whether the response was served from the browser's disk cache.
#
# @return [Boolean]
#
def from_disk_cache?
@response["fromDiskCache"] == true
end

#
# Whether a service worker answered the request instead of the network.
#
# @return [Boolean]
#
def from_service_worker?
@response["fromServiceWorker"] == true
end

# See https://crbug.com/883475
# Sometimes we never get the Network.responseReceived event.
# See https://crbug.com/764946
Expand Down
11 changes: 6 additions & 5 deletions lib/ferrum/page.rb
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def javascript?
# page.position # => [10, 20]
#
def position
window_bounds.values_at("left", "top")
window_bounds.values_at(:left, :top)
end

#
Expand Down Expand Up @@ -246,17 +246,18 @@ def window_bounds=(bounds)
end

#
# Current window bounds.
# Current window bounds, in the shape {#window_bounds=} takes.
#
# @return [Hash{String => (Integer, String)}]
# @return [Hash{Symbol => (Integer, String)}]
#
# @raise [TimeoutError]
#
# @example
# page.window_bounds # => { "left": 0, "top": 1286, "width": 10, "height": 10, "windowState": "normal" }
# page.window_bounds # => { left: 0, top: 1286, width: 10, height: 10, window_state: "normal" }
#
def window_bounds
command("Browser.getWindowBounds", windowId: window_id).fetch("bounds")
bounds = command("Browser.getWindowBounds", windowId: window_id).fetch("bounds")
bounds.transform_keys { |k| k == "windowState" ? :window_state : k.to_sym }
end

#
Expand Down
Loading
Loading