Skip to content

Commit

Permalink
Allow subscriptions to be removed (#455)
Browse files Browse the repository at this point in the history
  • Loading branch information
rzane authored Jan 8, 2025
1 parent 4ede96c commit a49a934
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
8 changes: 8 additions & 0 deletions lib/ferrum/client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,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
Expand Down Expand Up @@ -101,6 +105,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
Expand Down
5 changes: 5 additions & 0 deletions lib/ferrum/client/subscriber.rb
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,11 @@ def <<(message)
def on(event, &block)
@on[event] ||= Concurrent::Array.new
@on[event] << block
@on[event].index(block)
end

def off(event, id)
@on[event].delete_at(id)
true
end

Expand Down
13 changes: 13 additions & 0 deletions lib/ferrum/page.rb
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,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
Expand Down
38 changes: 38 additions & 0 deletions spec/page_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,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

0 comments on commit a49a934

Please sign in to comment.