Class: Ferrum::Browser::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/ferrum/browser/client.rb

Instance Method Summary collapse

Constructor Details

#initialize(browser, ws_url, start_id = 0, allow_slowmo = true) ⇒ Client

Returns a new instance of Client.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/ferrum/browser/client.rb', line 10

def initialize(browser, ws_url, start_id = 0, allow_slowmo = true)
  @command_id = start_id
  @pendings = Concurrent::Hash.new
  @browser = browser
  @slowmo = @browser.slowmo if allow_slowmo && @browser.slowmo > 0
  @ws = WebSocket.new(ws_url, @browser.logger)
  @subscriber = Subscriber.new

  @thread = Thread.new do
    while message = @ws.messages.pop
      if message.key?("method")
        @subscriber.async.call(message)
      else
        @pendings[message["id"]]&.set(message)
      end
    end
  end
end

Instance Method Details

#closeObject



49
50
51
52
53
54
55
56
# File 'lib/ferrum/browser/client.rb', line 49

def close
  @ws.close
  # Give a thread some time to handle a tail of messages
  @pendings.clear
  Timeout.timeout(1) { @thread.join }
rescue Timeout::Error
  @thread.kill
end

#command(method, params = {}) ⇒ Object

Raises:



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ferrum/browser/client.rb', line 29

def command(method, params = {})
  pending = Concurrent::IVar.new
  message = build_message(method, params)
  @pendings[message[:id]] = pending
  sleep(@slowmo) if @slowmo
  @ws.send_message(message)
  data = pending.value!(@browser.timeout)
  @pendings.delete(message[:id])

  raise DeadBrowser if data.nil? && @ws.messages.closed?
  raise TimeoutError unless data
  error, response = data.values_at("error", "result")
  raise BrowserError.new(error) if error
  response
end

#on(event, &block) ⇒ Object



45
46
47
# File 'lib/ferrum/browser/client.rb', line 45

def on(event, &block)
  @subscriber.on(event, &block)
end