class ChromeRemote::Client

Attributes

handlers[R]
ws[R]

Public Class Methods

new(ws_url) click to toggle source
# File lib/chrome_remote/client.rb, line 8
def initialize(ws_url)
  @ws = WebSocketClient.new(ws_url)
  @handlers = Hash.new { |hash, key| hash[key] = [] }
end

Public Instance Methods

listen() click to toggle source
# File lib/chrome_remote/client.rb, line 30
def listen
  read_until { false }
end
listen_until(&block) click to toggle source
# File lib/chrome_remote/client.rb, line 26
def listen_until(&block)
  read_until { block.call }
end
on(event_name, &block) click to toggle source
# File lib/chrome_remote/client.rb, line 22
def on(event_name, &block)
  handlers[event_name] << block
end
send_cmd(command, params = {}) click to toggle source
# File lib/chrome_remote/client.rb, line 13
def send_cmd(command, params = {})
  msg_id = generate_unique_id

  ws.send_msg({method: command, params: params, id: msg_id}.to_json)

  msg = read_until { |msg| msg["id"] == msg_id }
  Hashie::Mash.new(msg["result"])
end
wait_for(event_name=nil, timeout: nil) { |msg, msg| ... } click to toggle source
# File lib/chrome_remote/client.rb, line 34
def wait_for(event_name=nil, timeout: nil)
  Timeout::timeout(timeout) do
    if event_name
      msg = read_until { |msg| msg["method"] == event_name }
    elsif block_given?
      msg = read_until { |msg| yield(msg["method"], msg["params"]) }
    end
    Hashie::Mash.new(msg["params"])
  end
end

Private Instance Methods

generate_unique_id() click to toggle source
# File lib/chrome_remote/client.rb, line 47
def generate_unique_id
  @last_id ||= 0
  @last_id += 1
end
read_msg() click to toggle source
# File lib/chrome_remote/client.rb, line 52
def read_msg
  msg = JSON.parse(ws.read_msg)

  # Check if it’s an event and invoke any handlers
  if event_name = msg["method"]
    handlers[event_name].each do |handler|
      handler.call(msg["params"])
    end
  end

  msg
end
read_until(&block) click to toggle source
# File lib/chrome_remote/client.rb, line 65
def read_until(&block)
  loop do
    msg = read_msg
    return msg if block.call(msg)
  end
end