diff --git a/CHANGELOG.md b/CHANGELOG.md index 029778c8..d28d2acf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,10 @@ pending, when the page doesn't load in time ### Changed +- `page.on(:request)`, `on(:auth)` and `on(:dialog)` callbacks form a chain: they run in order and the rest are skipped + once one continues, responds to, aborts, accepts or dismisses, and an unhandled request is continued. They receive + only the object, not `index` and `total`, use `handled?` to check whether a previous callback took it. A callback + that holds a request to answer later gets it continued, and one registered after the handler no longer sees it - `page.cookies` is the cookies the page sees, the ones sent to its URL and its frames' URLs, or `each(urls:)`. It returned every cookie in the context, use `browser.cookies` or `browser.contexts[page.context_id].cookies` for that. `set` and `remove` default to the page's host, `clear` keeps other domains, `store`/`load` are on the context only @@ -30,6 +34,9 @@ `go_to` instead ### Fixed +- `page.on(:request, &:continue)` never continued the request, it called `continue(index, total)` and the error was + dropped. Symbol procs and lambdas taking one argument get only the object now, for `:request`, `:response`, `:auth` + and `:dialog` - `AuthRequest#abort` raised `BrowserError` and left the page hanging, it cancels the auth challenge now - `InterceptedRequest#navigation_request?` and `AuthRequest#navigation_request?` always returned `nil`, they are true for document requests now diff --git a/docs/16-dialogs.md b/docs/16-dialogs.md index 6e2f9c2c..99ba1b91 100644 --- a/docs/16-dialogs.md +++ b/docs/16-dialogs.md @@ -14,6 +14,9 @@ Accept dialog with given text or default prompt if applicable Dismiss dialog +Callbacks run in the order they were added and the rest are skipped once one accepts or dismisses the dialog. A dialog +nobody handled is accepted with a warning. + ```ruby page.on(:dialog) do |dialog| if dialog.match?(/bla-bla/) diff --git a/docs/7-network.md b/docs/7-network.md index 425edea3..7c64db3b 100644 --- a/docs/7-network.md +++ b/docs/7-network.md @@ -92,8 +92,10 @@ Subscribes to a CDP event, or to one of the following pseudo-events. Returns a subscription id you can pass to `off` to unsubscribe. * `:request` an intercepted request, see `intercept` below. Requires `network.intercept` to be set up first. + Callbacks run in the order they were added and the rest are skipped once one handles the request. * `:response` a request's response once it's fully loaded, see below. Works without `intercept`. * `:auth` a proxy/basic auth challenge, see `authorize` below. Requires `network.intercept` to be set up first. + Works like `:request`, an unhandled challenge gets Chrome's default response. * `:dialog` a JS dialog (`alert`/`confirm`/`prompt`), see [Dialogs](./16-dialogs.md). * anything else is passed straight through as a raw CDP event name, e.g. `page.on("Page.frameNavigated") { |params| ... }`. @@ -133,8 +135,16 @@ Set request interception for given options. This method is only sets request interception, you should use `on` callback to catch requests and abort or continue them. -Every paused request has to be continued, aborted or responded to by one of your `on(:request)` callbacks, including -ones that only log or inspect it. A request nobody handles stays paused, and the page waits for it until it times out. +`on(:request)` callbacks run in the order they were added and receive only the request. The first one that continues, +responds to or aborts it handles it and the rest are skipped, so a callback that doesn't care about a request just +returns. A request no callback handled is continued. + +```ruby +page.on(:request) { |request| request.abort if request.match?(/ads/) } +page.on(:request) { |request| request.respond(body: "stub") if request.match?(/api/) } +``` + +`request.handled?` tells whether it was already handled. * options `Hash` * :pattern `String` \* by default diff --git a/docs/9-proxy.md b/docs/9-proxy.md index 6d0c6103..677f7e82 100644 --- a/docs/9-proxy.md +++ b/docs/9-proxy.md @@ -37,8 +37,8 @@ end ## Intercepting requests behind a proxy A proxy with `:user` and `:password` is authorized through request interception, so Ferrum continues every request -for you as long as nothing else subscribes to `on(:request)`. Once you subscribe, or set `network.blacklist` or -`network.whitelist`, your code takes over and has to continue or abort every request: +nothing else handles. Your `on(:request)` callbacks, `network.blacklist` and `network.whitelist` run first and can +continue, respond to or abort a request, the rest are continued: ```ruby browser = Ferrum::Browser.new(proxy: { host: "x.x.x.x", port: "8800", user: "user", password: "pa$$" }) diff --git a/lib/ferrum/client/subscriber.rb b/lib/ferrum/client/subscriber.rb index bda895d0..000201cc 100644 --- a/lib/ferrum/client/subscriber.rb +++ b/lib/ferrum/client/subscriber.rb @@ -78,7 +78,7 @@ def off(event, id) # @return [Boolean] # def subscribed?(event) - @on.key?(event) + @on[event].to_a.any? end # diff --git a/lib/ferrum/dialog.rb b/lib/ferrum/dialog.rb index 16a061cf..08d92305 100644 --- a/lib/ferrum/dialog.rb +++ b/lib/ferrum/dialog.rb @@ -14,6 +14,16 @@ def initialize(page, params) @page = page @message = params["message"] @default_prompt = params["defaultPrompt"] + @handled = false + end + + # + # Whether the dialog was accepted or dismissed. + # + # @return [Boolean] + # + def handled? + @handled end # @@ -36,6 +46,7 @@ def accept(prompt_text = nil) options = { accept: true } response = prompt_text || default_prompt options.merge!(promptText: response) if response + @handled = true @page.command("Page.handleJavaScriptDialog", slowmoable: true, **options) end @@ -54,6 +65,7 @@ def accept(prompt_text = nil) # browser.go_to("https://google.com") # def dismiss + @handled = true @page.command("Page.handleJavaScriptDialog", slowmoable: true, accept: false) end diff --git a/lib/ferrum/interceptable.rb b/lib/ferrum/interceptable.rb index 9c4581c7..0aaab60b 100644 --- a/lib/ferrum/interceptable.rb +++ b/lib/ferrum/interceptable.rb @@ -1,5 +1,7 @@ # frozen_string_literal: true +require "ferrum/interceptable/chain" + module Ferrum # Shared by {Page} and {Worker}: subscribes to the CDP events behind the # `:request` (Fetch-domain request interception), `:response` (a request's @@ -10,6 +12,11 @@ module Ferrum module Interceptable # Subscribes to a CDP event, or to `:request`/`:response`/`:auth`/`:console`. # + # `:request` and `:auth` callbacks form a chain: they run in the order they + # were added, and the rest are skipped as soon as one of them handles the + # object (`continue`, `respond`, `abort`). An object nobody handled is + # continued, an auth challenge gets Chrome's default response. + # # @param [Symbol, String] name # # @yieldparam [Network::InterceptedRequest, Network::Exchange, Network::AuthRequest, Console::Message, Hash] arg @@ -17,41 +24,28 @@ module Interceptable # `:response`, the finished {Network::Exchange}. For `:auth`, the # {Network::AuthRequest} challenge. For `:console`, the new # {Console::Message}. For any other (raw CDP) event name, the event's - # params `Hash`. - # - # @yieldparam [Integer] index - # This callback's position among all callbacks currently registered for - # the event. Not passed for `:console`. - # - # @yieldparam [Integer] total - # Total number of callbacks currently registered for the event. Not - # passed for `:console`. + # params `Hash`, followed by the callback's index and the total number + # of callbacks registered for the event. # # @return [Integer] # The subscription id, used to unsubscribe via {#off}. # # @example # page.on(:console) { |message| warn(message) if message.error? } + # + # @example + # page.on(:request) { |r| r.abort if r.match?(/ads/) } + # page.on(:request) { |r| r.respond(body: "stub") if r.match?(/api/) } def on(name, &block) case name when :console console.on(&block) - when :request - client.on("Fetch.requestPaused") do |params, index, total| - request = Network::InterceptedRequest.new(client, params) - exchange = network.find_or_build_exchange(request.network_id) - exchange.intercepted_request = request - block.call(request, index, total) - end + when :request, :auth + chain(name).add(&block) when :response - client.on("Network.loadingFinished") do |params, index, total| + client.on("Network.loadingFinished") do |params| exchange = network.select(params["requestId"]).last - block.call(exchange, index, total) if exchange - end - when :auth - client.on("Fetch.authRequired") do |params, index, total| - request = Network::AuthRequest.new(self, params) - block.call(request, index, total) + block.call(exchange) if exchange end else client.on(name, &block) @@ -70,12 +64,10 @@ def off(name, id) case name when :console console.off(id) - when :request - client.off("Fetch.requestPaused", id) + when :request, :auth + chain(name).remove(id) when :response client.off("Network.loadingFinished", id) - when :auth - client.off("Fetch.authRequired", id) else client.off(name, id) end @@ -89,5 +81,30 @@ def off(name, id) def subscribed?(event) client.subscribed?(event) end + + private + + def chain(name) + @chains ||= Concurrent::Hash.new + @chains[name] ||= build_chain(name) + end + + def build_chain(name) + case name + when :request + Chain.new(client, "Fetch.requestPaused", + build: lambda do |params| + request = Network::InterceptedRequest.new(client, params) + exchange = network.find_or_build_exchange(request.network_id) + exchange.intercepted_request = request + request + end, + default: lambda(&:continue)) + when :auth + Chain.new(client, "Fetch.authRequired", + build: ->(params) { Network::AuthRequest.new(self, params) }, + default: ->(request) { request.continue(authChallengeResponse: { response: "Default" }) }) + end + end end end diff --git a/lib/ferrum/interceptable/chain.rb b/lib/ferrum/interceptable/chain.rb new file mode 100644 index 00000000..8c079665 --- /dev/null +++ b/lib/ferrum/interceptable/chain.rb @@ -0,0 +1,99 @@ +# frozen_string_literal: true + +module Ferrum + module Interceptable + # + # An ordered chain of handlers for an event that has to be answered + # exactly once, e.g. a paused request or a dialog. Handlers run in the + # order they were added and the chain stops at the first one that handles + # the event object, so a handler that doesn't want the object just + # returns. An object nobody handled is passed to the default action. + # + class Chain + # @param [#on, #off] client + # Where the event comes from. + # + # @param [String] event + # The CDP event name. + # + # @param [#call] build + # Turns the event params into the object handlers receive. The object + # has to respond to `handled?`. + # + # @param [#call] default + # Called with the object when no handler handled it. + # + # @param [Boolean] persistent + # Keep listening to the event while no handlers are left, so the + # default action still applies. + def initialize(client, event, build:, default:, persistent: false) + @client = client + @event = event + @build = build + @default = default + @handlers = Concurrent::Hash.new + @sequence = Concurrent::AtomicFixnum.new + @subscription = nil + @persistent = persistent + @mutex = Mutex.new + @mutex.synchronize { subscribe } if persistent + end + + # + # Adds a handler to the end of the chain. + # + # @return [Integer] + # The id to pass to {#remove}. + # + def add(&block) + id = @sequence.increment + @mutex.synchronize do + @handlers[id] = block + subscribe + end + id + end + + # + # Removes a handler, and stops listening to the event once no handlers + # are left. + # + # @param [Integer] id + # The id returned by {#add}. + # + # @return [void] + # + def remove(id) + @mutex.synchronize do + @handlers.delete(id) + next if @persistent || @handlers.any? || @subscription.nil? + + @client.off(@event, @subscription) + @subscription = nil + end + end + + private + + def subscribe + @subscribe ||= @client.on(@event) { |params| run(params) } + end + + def run(params) + object = @build.call(params) + @handlers.each_value do |handler| + break if object.handled? + + call(handler, object) + end + @default.call(object) unless object.handled? + end + + def call(handler, object) + handler.call(object) + rescue StandardError => e + warn("Ferrum: #{@event} callback raised #{e.class}: #{e.message}\n #{e.backtrace&.first}") + end + end + end +end diff --git a/lib/ferrum/network.rb b/lib/ferrum/network.rb index a25bd8ce..90c5462e 100644 --- a/lib/ferrum/network.rb +++ b/lib/ferrum/network.rb @@ -318,19 +318,15 @@ def authorize(user:, password:, type: :server, &block) @page.on(:request, &block) - @page.on(:auth) do |request, index, total| - if request.auth_challenge?(type) - response = authorized_response(@authorized_ids[type], - request.request_id, - user, password) - - @authorized_ids[type] << request.request_id - request.continue(authChallengeResponse: response) - elsif index + 1 < total - next # There are other callbacks that can handle this - else - request.abort - end + @page.on(:auth) do |request| + next unless request.auth_challenge?(type) + + response = authorized_response(@authorized_ids[type], + request.request_id, + user, password) + + @authorized_ids[type] << request.request_id + request.continue(authChallengeResponse: response) end end diff --git a/lib/ferrum/network/auth_request.rb b/lib/ferrum/network/auth_request.rb index e4a6e5d0..9d64957e 100644 --- a/lib/ferrum/network/auth_request.rb +++ b/lib/ferrum/network/auth_request.rb @@ -17,6 +17,16 @@ def initialize(page, params) @frame_id = params["frameId"] @resource_type = params["resourceType"] @request = params["request"] + @handled = false + end + + # + # Whether the challenge was answered or canceled. + # + # @return [Boolean] + # + def handled? + @handled end # @@ -73,6 +83,7 @@ def match?(pattern) # def continue(**options) options = options.merge(requestId: request_id) + @handled = true @page.command("Fetch.continueWithAuth", **options) end diff --git a/lib/ferrum/network/intercepted_request.rb b/lib/ferrum/network/intercepted_request.rb index d3e3fbef..0bf4e11a 100644 --- a/lib/ferrum/network/intercepted_request.rb +++ b/lib/ferrum/network/intercepted_request.rb @@ -38,6 +38,15 @@ def status?(value) @status == value.to_sym end + # + # Whether the request was continued, responded to or aborted. + # + # @return [Boolean] + # + def handled? + !@status.nil? + end + # # Whether this request is for the navigation of a frame, as opposed # to a subresource (script, image, XHR, etc). diff --git a/lib/ferrum/page.rb b/lib/ferrum/page.rb index 24347eee..83daf44d 100644 --- a/lib/ferrum/page.rb +++ b/lib/ferrum/page.rb @@ -571,13 +571,10 @@ def command(method, wait: 0, slowmoable: false, timeout: nil, **params) # # @return [Integer] # The subscription id, used to unsubscribe via {#off}. - def on(name, &block) + def on(name, &) return super unless name == :dialog - client.on("Page.javascriptDialogOpening") do |params, index, total| - dialog = Dialog.new(self, params) - block.call(dialog, index, total) - end + chain(:dialog).add(&) end # Unsubscribes a listener previously registered via {#on}. @@ -591,7 +588,7 @@ def on(name, &block) def off(name, id) return super unless name == :dialog - client.off("Page.javascriptDialogOpening", id) + chain(:dialog).remove(id) end # Whether the page is configured to use a proxy. @@ -644,13 +641,21 @@ def subscribe end end - on(:dialog) do |dialog, _index, total| - if total == 1 - warn "Dialog was shown but you didn't provide `on(:dialog)` callback, accepting it by default. " \ - "Please take a look at https://github.com/rubycdp/ferrum#dialogs" - dialog.accept - end - end + chain(:dialog) + end + + def build_chain(name) + return super unless name == :dialog + + Chain.new(client, "Page.javascriptDialogOpening", + build: ->(params) { Dialog.new(self, params) }, + default: method(:accept_dialog), persistent: true) + end + + 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" + dialog.accept end def prepare_page @@ -665,9 +670,7 @@ def prepare_page if use_authorized_proxy? network.authorize(user: @proxy_user, password: @proxy_password, - type: :proxy) do |request, _index, total| - request.continue if total == 1 - end + type: :proxy) { |_request| nil } end downloads.set_behavior(save_path: @options.save_path) if @options.save_path diff --git a/sig/ferrum/dialog.rbs b/sig/ferrum/dialog.rbs index e0b1cae2..f7697ab4 100644 --- a/sig/ferrum/dialog.rbs +++ b/sig/ferrum/dialog.rbs @@ -7,9 +7,12 @@ module Ferrum @page: Page @message: String @default_prompt: String? + @handled: bool def initialize: (Page page, Hash[String, untyped] params) -> void + def handled?: () -> bool + def accept: (?String? prompt_text) -> Hash[String, untyped] def dismiss: () -> Hash[String, untyped] diff --git a/sig/ferrum/interceptable.rbs b/sig/ferrum/interceptable.rbs index 7271aafa..84862afa 100644 --- a/sig/ferrum/interceptable.rbs +++ b/sig/ferrum/interceptable.rbs @@ -1,13 +1,21 @@ module Ferrum module Interceptable - def on: (:request) { (Network::InterceptedRequest, Integer, Integer) -> void } -> Integer - | (:response) { (Network::Exchange, Integer, Integer) -> void } -> Integer - | (:auth) { (Network::AuthRequest, Integer, Integer) -> void } -> Integer + def on: (:request) { (Network::InterceptedRequest) -> void } -> Integer + | (:response) { (Network::Exchange) -> void } -> Integer + | (:auth) { (Network::AuthRequest) -> void } -> Integer | (:console) { (Console::Message) -> void } -> Integer - | (Symbol | String name) { (*untyped) -> void } -> Integer + | (Symbol | String name) { (Hash[String, untyped], Integer, Integer) -> void } -> Integer def off: (Symbol | String name, Integer id) -> void def subscribed?: (String event) -> bool + + private + + @chains: Concurrent::Hash[Symbol, Chain[untyped]] + + def chain: (Symbol name) -> Chain[untyped] + + def build_chain: (Symbol name) -> Chain[untyped] end end diff --git a/sig/ferrum/interceptable/chain.rbs b/sig/ferrum/interceptable/chain.rbs new file mode 100644 index 00000000..ea640360 --- /dev/null +++ b/sig/ferrum/interceptable/chain.rbs @@ -0,0 +1,33 @@ +module Ferrum + module Interceptable + class Chain[T < _Handleable] + interface _Handleable + def handled?: () -> bool + end + + @client: untyped + @event: String + @build: ^(Hash[String, untyped]) -> T + @default: ^(T) -> untyped + @handlers: Concurrent::Hash[Integer, ^(T) -> untyped] + @sequence: Concurrent::AtomicFixnum + @subscription: Integer? + @persistent: bool + @mutex: Mutex + + def initialize: (untyped client, String event, build: ^(Hash[String, untyped]) -> T, default: ^(T) -> untyped, ?persistent: bool) -> void + + def add: () { (T) -> untyped } -> Integer + + def remove: (Integer id) -> void + + private + + def subscribe: () -> void + + def run: (Hash[String, untyped] params) -> void + + def call: (^(T) -> untyped handler, T object) -> void + end + end +end diff --git a/sig/ferrum/network/auth_request.rbs b/sig/ferrum/network/auth_request.rbs index 80a38f9f..790f91f0 100644 --- a/sig/ferrum/network/auth_request.rbs +++ b/sig/ferrum/network/auth_request.rbs @@ -11,6 +11,10 @@ module Ferrum def initialize: (Page page, Hash[::String, untyped] params) -> void + @handled: bool + + def handled?: () -> bool + def navigation_request?: () -> bool def auth_challenge?: ((::String | ::Symbol) source) -> bool diff --git a/sig/ferrum/network/intercepted_request.rbs b/sig/ferrum/network/intercepted_request.rbs index 73c70fc3..3c34cc77 100644 --- a/sig/ferrum/network/intercepted_request.rbs +++ b/sig/ferrum/network/intercepted_request.rbs @@ -15,6 +15,8 @@ module Ferrum def status?: (untyped value) -> untyped + def handled?: () -> bool + def navigation_request?: () -> bool def match?: (untyped regexp) -> untyped diff --git a/sig/ferrum/page.rbs b/sig/ferrum/page.rbs index 3c0d41f8..1884aa85 100644 --- a/sig/ferrum/page.rbs +++ b/sig/ferrum/page.rbs @@ -96,12 +96,12 @@ module Ferrum def command: (String method, ?wait: ::Numeric?, ?slowmoable: bool, ?timeout: ::Numeric?, **untyped) -> Hash[String, untyped] - def on: (:dialog) { (Dialog, Integer, Integer) -> void } -> Integer + def on: (:dialog) { (Dialog) -> void } -> Integer | (:console) { (Console::Message) -> void } -> Integer - | (:request) { (Network::InterceptedRequest, Integer, Integer) -> void } -> Integer - | (:response) { (Network::Exchange, Integer, Integer) -> void } -> Integer - | (:auth) { (Network::AuthRequest, Integer, Integer) -> void } -> Integer - | ((Symbol | String) event) { (*untyped) -> void } -> Integer + | (:request) { (Network::InterceptedRequest) -> void } -> Integer + | (:response) { (Network::Exchange) -> void } -> Integer + | (:auth) { (Network::AuthRequest) -> void } -> Integer + | ((Symbol | String) event) { (Hash[String, untyped], Integer, Integer) -> void } -> Integer def off: ((Symbol | String) event, Integer id) -> void @@ -117,6 +117,10 @@ module Ferrum def subscribe: () -> void + def build_chain: (Symbol name) -> Interceptable::Chain[untyped] + + def accept_dialog: (Dialog dialog) -> Hash[String, untyped] + def prepare_page: () -> void def history_navigate: (::Integer delta) -> Hash[String, untyped] diff --git a/spec/dialog_spec.rb b/spec/dialog_spec.rb index 5fdbcf2c..b60c2b77 100644 --- a/spec/dialog_spec.rb +++ b/spec/dialog_spec.rb @@ -2,7 +2,7 @@ describe Ferrum::Dialog do def open_prompt(&block) - browser.on(:dialog) { |dialog, _index, _total| block.call(dialog) } + browser.on(:dialog) { |dialog| block.call(dialog) } browser.go_to browser.execute(%(setTimeout(() => window.result = prompt("Your name?", "Bob")))) end @@ -34,7 +34,7 @@ def open_prompt(&block) describe "#accept" do it "works with nested modals" do browser.go_to("/with_js") - browser.on(:dialog) do |dialog, _index, _total| + browser.on(:dialog) do |dialog| if dialog.match?("Are you sure?") dialog.accept else @@ -56,9 +56,7 @@ def open_prompt(&block) popup, = browser.windows(:last) - popup.on(:dialog) do |dialog, _index, _total| - dialog.accept - end + popup.on(:dialog, &:accept) popup.at_css("a#open-match").click expect(popup.at_xpath("//a[@id='open-match' and @confirmed='true']")).to be @@ -88,9 +86,7 @@ def open_prompt(&block) popup, = browser.windows(:last) - popup.on(:dialog) do |dialog, _index, _total| - dialog.dismiss - end + popup.on(:dialog, &:dismiss) popup.at_css("a#open-match").click expect(popup.at_xpath("//a[@id='open-match' and @confirmed='true']")).not_to be @@ -108,7 +104,7 @@ def open_prompt(&block) describe "#match?" do it "matches on partial strings" do browser.go_to("/with_js") - browser.on(:dialog) do |dialog, _index, _total| + browser.on(:dialog) do |dialog| if dialog.match?("[reg.exp] (chara©+er$)") dialog.accept else @@ -123,7 +119,7 @@ def open_prompt(&block) it "treats string patterns literally instead of as regexps" do browser.go_to("/with_js") - browser.on(:dialog) do |dialog, _index, _total| + browser.on(:dialog) do |dialog| if dialog.match?("[reg.exp?]") dialog.accept else @@ -138,7 +134,7 @@ def open_prompt(&block) it "matches on regular expressions" do browser.go_to("/with_js") - browser.on(:dialog) do |dialog, _index, _total| + browser.on(:dialog) do |dialog| if dialog.match?(/^.t.ext.*\[\w{3}\.\w{3}\]/i) dialog.accept else diff --git a/spec/network/auth_request_spec.rb b/spec/network/auth_request_spec.rb index 3025750c..4baf6ab6 100644 --- a/spec/network/auth_request_spec.rb +++ b/spec/network/auth_request_spec.rb @@ -42,8 +42,8 @@ describe "#continue" do it "answers the auth challenge with the given response" do network.intercept - page.on(:request) { |request, _index, _total| request.continue } - page.on(:auth) do |request, _index, _total| + page.on(:request, &:continue) + page.on(:auth) do |request| request.continue(authChallengeResponse: { response: "ProvideCredentials", username: "login", password: "pass" }) end @@ -57,8 +57,8 @@ describe "#abort" do it "cancels the auth challenge and lets the page load the unauthorized response" do network.intercept - page.on(:request) { |request, _index, _total| request.continue } - page.on(:auth) { |request, _index, _total| request.abort } + page.on(:request, &:continue) + page.on(:auth, &:abort) page.go_to("/basic_auth") @@ -90,8 +90,8 @@ def auth_request(path) challenged = nil network.intercept - page.on(:request) { |request, _index, _total| request.continue } - page.on(:auth) do |request, _index, _total| + page.on(:request, &:continue) + page.on(:auth) do |request| challenged ||= request request.continue(authChallengeResponse: { response: "CancelAuth" }) end diff --git a/spec/network/intercepted_request_spec.rb b/spec/network/intercepted_request_spec.rb index 06e38611..01937f60 100644 --- a/spec/network/intercepted_request_spec.rb +++ b/spec/network/intercepted_request_spec.rb @@ -109,7 +109,7 @@ describe "#continue" do it "lets the request through" do network.intercept - page.on(:request) { |request, _index, _total| request.continue } + page.on(:request, &:continue) page.go_to @@ -132,7 +132,7 @@ describe "#abort" do it "fails the request as blocked by the client" do network.intercept - page.on(:request) { |request, _index, _total| request.abort } + page.on(:request, &:abort) expect { page.go_to }.to raise_error(Ferrum::StatusError, /net::ERR_BLOCKED_BY_CLIENT/) expect(last_exchange.blocked?).to be(true) diff --git a/spec/network_spec.rb b/spec/network_spec.rb index 76deefd9..4616a53e 100644 --- a/spec/network_spec.rb +++ b/spec/network_spec.rb @@ -323,7 +323,7 @@ it "works with other subscriptions" do @intercepted_request = nil - page.on(:request) do |request, _index, _total| + page.on(:request) do |request| @intercepted_request ||= request end @@ -488,9 +488,7 @@ it "raises no error when authorize is with block" do expect do - network.authorize(user: "login", password: "pass") do |request, _index, _total| - request.continue - end + network.authorize(user: "login", password: "pass", &:continue) end.not_to raise_error end @@ -512,9 +510,7 @@ end it "allows with given credentials" do - network.authorize(user: "login", password: "pass") do |request, _index, _total| - request.continue - end + network.authorize(user: "login", password: "pass", &:continue) page.go_to("/basic_auth") @@ -523,9 +519,7 @@ end it "allows even overwriting headers" do - network.authorize(user: "login", password: "pass") do |request, _index, _total| - request.continue - end + network.authorize(user: "login", password: "pass", &:continue) page.headers.set("Cuprite" => "true") page.go_to("/basic_auth") @@ -535,9 +529,7 @@ end it "denies with wrong credentials" do - network.authorize(user: "user", password: "pass!") do |request, _index, _total| - request.continue - end + network.authorize(user: "user", password: "pass!", &:continue) page.go_to("/basic_auth") @@ -546,9 +538,7 @@ end it "allows on POST request" do - network.authorize(user: "login", password: "pass") do |request, _index, _total| - request.continue - end + network.authorize(user: "login", password: "pass", &:continue) page.go_to("/basic_auth") page.at_css(%([type="submit"])).click diff --git a/spec/page_spec.rb b/spec/page_spec.rb index 356e007f..cd3b4d65 100644 --- a/spec/page_spec.rb +++ b/spec/page_spec.rb @@ -484,10 +484,63 @@ def is_mobile? end end + context "with :request" do + it "continues the request when given the continue method as a block" do + network.intercept + page.on(:request, &:continue) + + page.go_to("/foo") + + expect(page.body).to include("Another World") + end + + it "skips the remaining callbacks once one handles the request" do + network.intercept + later = [] + page.on(:request, &:abort) + page.on(:request) { |request| later << request.url } + + expect { page.go_to("/foo") }.to raise_error(Ferrum::StatusError) + + expect(later).to be_empty + end + + it "passes the request to the next callback when one doesn't handle it" do + network.intercept + page.on(:request) { |request| request.abort if request.match?(/nothing/) } + page.on(:request, &:continue) + + page.go_to("/foo") + + expect(page.body).to include("Another World") + end + + it "continues the request when no callback handles it" do + network.intercept + page.on(:request) { |request| request.match?(/nothing/) } + + page.go_to("/foo") + + expect(page.body).to include("Another World") + end + + it "stops calling a callback once it is unsubscribed" do + network.intercept + seen = [] + id = page.on(:request) { |request| seen << request.url } + page.on(:request, &:continue) + + page.off(:request, id) + page.go_to("/foo") + + expect(seen).to be_empty + end + end + context "with :response" do it "yields the exchange once its response is fully loaded" do exchanges = [] - page.on(:response) { |exchange, _index, _total| exchanges << exchange } + page.on(:response) { |exchange| exchanges << exchange } page.go_to("/foo") @@ -498,7 +551,7 @@ def is_mobile? it "fires once per exchange that finishes loading" do exchanges = [] - page.on(:response) { |exchange, _index, _total| exchanges << exchange } + page.on(:response) { |exchange| exchanges << exchange } page.go_to("/with_js") @@ -507,7 +560,7 @@ def is_mobile? it "does not fire for requests that fail to load" do exchanges = [] - page.on(:response) { |exchange, _index, _total| exchanges << exchange } + page.on(:response) { |exchange| exchanges << exchange } page.go_to("/with_ajax_connection_refused") network.wait_for_idle @@ -521,7 +574,7 @@ def is_mobile? expect(page.subscribed?("Fetch.requestPaused")).to eq(false) exchange = nil - page.on(:response) { |e, _index, _total| exchange = e } + page.on(:response) { |e| exchange = e } page.go_to("/foo") expect(exchange).to be