module Selenium::WebDriver::DriverExtensions::HasLogEvents

def log_console_events

def log_console_events
  devtools.runtime.on(:console_api_called) do |params|
    event = DevTools::ConsoleEvent.new(
      type: params['type'],
      timestamp: params['timestamp'],
      args: params['args']
    )
    log_listeners[:console].each do |listener|
      listener.call(event)
    end
  end
end

def log_exception_events

def log_exception_events
  devtools.runtime.on(:exception_thrown) do |params|
    description = if params.dig('exceptionDetails', 'exception')
                    params.dig('exceptionDetails', 'exception', 'description')
                  else
                    params.dig('exceptionDetails', 'text')
                  end
    event = DevTools::ExceptionEvent.new(
      description: description,
      timestamp: params['timestamp'],
      stacktrace: params.dig('exceptionDetails', 'stackTrace', 'callFrames')
    )
    log_listeners[:exception].each do |listener|
      listener.call(event)
    end
  end
end

def log_listeners

def log_listeners
  @log_listeners ||= Hash.new { |listeners, kind| listeners[kind] = [] }
end

def log_mutation_event(params)

def log_mutation_event(params)
  payload = JSON.parse(params['payload'])
  elements = find_elements(css: "*[data-__webdriver_id='#{payload['target']}']")
  return if elements.empty?
  event = DevTools::MutationEvent.new(
    element: elements.first,
    attribute_name: payload['name'],
    current_value: payload['value'],
    old_value: payload['oldValue']
  )
  log_listeners[:mutation].each do |log_listener|
    log_listener.call(event)
  end
end

def log_mutation_events

def log_mutation_events
  devtools.page.enable
  devtools.runtime.add_binding(name: '__webdriver_attribute')
  execute_script(mutation_listener)
  devtools.page.add_script_to_evaluate_on_new_document(source: mutation_listener)
  devtools.runtime.on(:binding_called) { |event| log_mutation_event(event) }
end

def mutation_listener

def mutation_listener
  @mutation_listener ||= read_atom(:mutationListener)
end

def on_log_event(kind, &block)

def on_log_event(kind, &block)
  if browser == :firefox
    WebDriver.logger.deprecate(
      'Driver#on_log_event on Firefox',
      'the script.add_console_message_handler or the script.add_javascript_error_handler methods',
      id: :on_log_event
    )
  end
  raise Error::WebDriverError, "Don't know how to handle #{kind} events" unless KINDS.include?(kind)
  enabled = log_listeners[kind].any?
  log_listeners[kind] << block
  return if enabled
  devtools.runtime.enable
  __send__(:"log_#{kind}_events")
end