Module: Ferrum::Page::Runtime

Included in:
Ferrum::Page
Defined in:
lib/ferrum/page/runtime.rb

Constant Summary collapse

INTERMITTENT_ATTEMPTS =
ENV.fetch("FERRUM_INTERMITTENT_ATTEMPTS", 6).to_i
INTERMITTENT_SLEEP =
ENV.fetch("FERRUM_INTERMITTENT_SLEEP", 0.1).to_f
EXECUTE_OPTIONS =
{
  returnByValue: true,
  functionDeclaration: %(function() { %s })
}.freeze
DEFAULT_OPTIONS =
{
  functionDeclaration: %(function() { return %s })
}.freeze
EVALUATE_ASYNC_OPTIONS =
{
  awaitPromise: true,
  functionDeclaration: %(
    function() {
     return new Promise((__resolve, __reject) => {
       try {
         arguments[arguments.length] = r => __resolve(r);
         arguments.length = arguments.length + 1;
         setTimeout(() => __reject(new Error("timed out promise")), %s);
         %s
       } catch(error) {
         __reject(error);
       }
     });
    }
  )
}.freeze

Instance Method Summary collapse

Instance Method Details

#evaluate(expression, *args) ⇒ Object



34
35
36
# File 'lib/ferrum/page/runtime.rb', line 34

def evaluate(expression, *args)
  call(*args, expression: expression)
end

#evaluate_async(expression, wait_time, *args) ⇒ Object



38
39
40
# File 'lib/ferrum/page/runtime.rb', line 38

def evaluate_async(expression, wait_time, *args)
  call(*args, expression: expression, wait_time: wait_time * 1000, **EVALUATE_ASYNC_OPTIONS)
end

#evaluate_on(node:, expression:, by_value: true, wait: 0) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/ferrum/page/runtime.rb', line 47

def evaluate_on(node:, expression:, by_value: true, wait: 0)
  errors = [NodeNotFoundError, NoExecutionContextError]
  attempts, sleep = INTERMITTENT_ATTEMPTS, INTERMITTENT_SLEEP

  Ferrum.with_attempts(errors: errors, max: attempts, wait: sleep) do
    response = command("DOM.resolveNode", nodeId: node.node_id)
    object_id = response.dig("object", "objectId")
    options = DEFAULT_OPTIONS.merge(objectId: object_id)
    options[:functionDeclaration] = options[:functionDeclaration] % expression
    options.merge!(returnByValue: by_value)

    response = command("Runtime.callFunctionOn",
                       wait: wait, **options)["result"]
                      .tap { |r| handle_error(r) }

    by_value ? response.dig("value") : handle_response(response)
  end
end

#execute(expression, *args) ⇒ Object



42
43
44
45
# File 'lib/ferrum/page/runtime.rb', line 42

def execute(expression, *args)
  call(*args, expression: expression, handle: false, **EXECUTE_OPTIONS)
  true
end