Class: Capybara::Cuprite::Browser::Client

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

Defined Under Namespace

Classes: IdError

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Client.



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

def initialize(browser, ws_url, allow_slowmo = true)
  @command_id = 0
  @subscribed = Hash.new { |h, k| h[k] = [] }
  @browser, @allow_slowmo = browser, allow_slowmo
  @commands = Queue.new
  @ws = WebSocket.new(ws_url, @browser.logger)

  @thread = Thread.new do
    while message = @ws.messages.pop
      method, params = message.values_at("method", "params")
      if method
        @subscribed[method].each { |b| b.call(params) }
      else
        @commands.push(message)
      end
    end

    @commands.close
  end
end

Instance Method Details

#closeObject



55
56
57
58
59
60
61
# File 'lib/capybara/cuprite/browser/client.rb', line 55

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

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



32
33
34
35
36
37
# File 'lib/capybara/cuprite/browser/client.rb', line 32

def command(method, params = {})
  message = build_message(method, params)
  sleep(@browser.slowmo) if !@browser.slowmo.nil? && @allow_slowmo
  @ws.send_message(message)
  message[:id]
end

#subscribe(event, &block) ⇒ Object



50
51
52
53
# File 'lib/capybara/cuprite/browser/client.rb', line 50

def subscribe(event, &block)
  @subscribed[event] << block
  true
end

#wait(id:) ⇒ Object



39
40
41
42
43
44
45
46
47
48
# File 'lib/capybara/cuprite/browser/client.rb', line 39

def wait(id:)
  message = Timeout.timeout(@browser.timeout, TimeoutError) { @commands.pop }
  raise DeadBrowser unless message
  raise IdError if message["id"] != id
  error, response = message.values_at("error", "result")
  raise BrowserError.new(error) if error
  response
rescue IdError
  retry
end