class ChromeRemote::Client

Attributes

handlers[R]
logger[R]
ws[R]

Public Class Methods

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

Public Instance Methods

listen() click to toggle source
# File lib/chrome_remote/client.rb, line 34
def listen
  read_until { false }
end
listen_until(&block) click to toggle source
# File lib/chrome_remote/client.rb, line 30
def listen_until(&block)
  read_until { block.call }
end
on(event_name, &block) click to toggle source
# File lib/chrome_remote/client.rb, line 26
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 15
def send_cmd(command, params = {})
  msg_id = generate_unique_id
  payload = {method: command, params: params, id: msg_id}.to_json

  logger.info "SEND ► #{payload}"
  ws.send_msg(payload)

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

Private Instance Methods

generate_unique_id() click to toggle source
# File lib/chrome_remote/client.rb, line 49
def generate_unique_id
  @last_id += 1
end
read_msg() click to toggle source
# File lib/chrome_remote/client.rb, line 53
def read_msg
  msg = ws.read_msg
  logger.info "◀ RECV #{msg}"
  msg = JSON.parse(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 68
def read_until(&block)
  loop do
    msg = read_msg
    return msg if block.call(msg)
  end
end