diff --git a/lib/ferrum/client.rb b/lib/ferrum/client.rb index 6e650a2a..71c3b78c 100644 --- a/lib/ferrum/client.rb +++ b/lib/ferrum/client.rb @@ -26,6 +26,10 @@ def on(event, &block) @client.on(event_name(event), &block) end + def off(event, id) + @client.off(event_name(event), id) + end + def subscribed?(event) @client.subscribed?(event_name(event)) end @@ -99,6 +103,10 @@ def on(event, &block) @subscriber.on(event, &block) end + def off(event, id) + @subscriber.off(event, id) + end + def subscribed?(event) @subscriber.subscribed?(event) end diff --git a/lib/ferrum/client/subscriber.rb b/lib/ferrum/client/subscriber.rb index 74b8887c..f10ceb72 100644 --- a/lib/ferrum/client/subscriber.rb +++ b/lib/ferrum/client/subscriber.rb @@ -23,6 +23,11 @@ def <<(message) def on(event, &block) @on[event] << block + @on[event].index(block) + end + + def off(event, id) + @on[event].delete_at(id) true end diff --git a/lib/ferrum/page.rb b/lib/ferrum/page.rb index 8f689ae4..d59a555a 100644 --- a/lib/ferrum/page.rb +++ b/lib/ferrum/page.rb @@ -379,6 +379,19 @@ def on(name, &block) end end + def off(name, id) + case name + when :dialog + client.off("Page.javascriptDialogOpening", id) + when :request + client.off("Fetch.requestPaused", id) + when :auth + client.off("Fetch.authRequired", id) + else + client.off(name, id) + end + end + def subscribed?(event) client.subscribed?(event) end diff --git a/spec/page_spec.rb b/spec/page_spec.rb index 8fc9be58..1250e750 100644 --- a/spec/page_spec.rb +++ b/spec/page_spec.rb @@ -194,4 +194,42 @@ expect(page.device_pixel_ratio).to eq(2) end end + + describe "#on" do + it "subscribes to an event" do + message = nil + + page.on("Runtime.consoleAPICalled") do |params| + message = params.dig("args", 0, "value") + end + + page.evaluate("console.log('hello')") + expect(message).to eq("hello") + end + end + + describe "#off" do + it "unsubscribes a specific event handler" do + message_a = nil + message_b = nil + + a = page.on("Runtime.consoleAPICalled") do |params| + message_a = params.dig("args", 0, "value") + end + + page.on("Runtime.consoleAPICalled") do |params| + message_b = params.dig("args", 0, "value") + end + + page.evaluate("console.log('hello')") + expect(message_a).to eq("hello") + expect(message_b).to eq("hello") + + page.off("Runtime.consoleAPICalled", a) + page.evaluate("console.log('goodbye')") + + expect(message_a).to eq("hello") + expect(message_b).to eq("goodbye") + end + end end