Module: Ferrum::Frame::Runtime

Included in:
Ferrum::Frame, IsolatedWorld, Worker
Defined in:
lib/ferrum/frame/runtime.rb,
sig/ferrum/frame/runtime.rbs

Overview

Runs JavaScript in a frame's execution context via Runtime.callFunctionOn, converting arguments and return values between Ruby and JS, and resolving object/array/node results into Ruby equivalents. A reference back to an enclosing object becomes CyclicObject.

There are three entry points, all of which accept the script in the same two shapes and pass arguments the same way:

Script shapes

A script is either code that gets wrapped in a function for you and returns the value of its last statement, or a function declaration, which is used as-is.

page.evaluate("window.scrollY")
page.evaluate("const a = 1\na + 1")
page.evaluate("function() { const a = 1; return a + 1 }")

Arrow functions keep the this of where they're defined, so on a Node use a function declaration when the script needs this.

Arguments

Keyword arguments become the function's parameters, so the script can name what it receives instead of digging through arguments[0]:

page.evaluate("a + b", a: 1, b: 2)

Each keyword is sent as its own protocol argument, so a Node arrives in JavaScript as the live element rather than as serialized JSON.

A function declaration names its parameters itself, so it takes positional arguments, in the order it declares them:

page.evaluate("function(a, b) { return a + b }", 1, 2)

Positional arguments also work with an expression, landing in arguments[0] and up, but can't be mixed with keyword ones.

timeout: is reserved for Ferrum, so a variable of the script can't take that name.

Promises

A returned promise, or any object with a then method, is awaited, so async/await works directly and there is no separate asynchronous method:

page.evaluate("await fetch(url).then(r => r.text())", url: "/api")

If the page navigates while the script awaits, the script isn't run again and ExecutionContextDestroyedError is raised.

Timeouts

If the script hasn't settled within timeout: seconds (defaulting to the page's timeout) a ScriptTimeoutError is raised.

The timeout is how long Ruby waits for Chrome's answer, so a page that replaces Promise or setTimeout can't defeat it, but it doesn't stop the script. A promise that never settles is harmless, while a synchronous endless loop keeps the page's JavaScript busy, so later calls on that page time out too. Other pages aren't affected.

How a call runs

All three methods, and their Node counterparts through #evaluate_in, take the same steps and differ only in a mode: :value, :handle or :none.

  1. Parse. Script reads the source once, skipping strings, template literals, regular expressions and comments. It finds the code without surrounding comments and semicolons, whether it's a function or arrow declaration, where its last statement starts, and whether it uses await.
  2. Arguments. timeout: is taken out of the keywords. Positional arguments are passed as they are. Named ones become the parameters of the function an expression is wrapped in, and raise for a declaration, which names its parameters itself.
  3. Wrap. A declaration is sent as it is. An expression becomes function(<names>) { return (<code>) }, async when it uses await. Of several statements, only the last is returned, as in function() { a(); return (b) }. #execute uses the script as written as the function body instead.
  4. Call. One Runtime.callFunctionOn in the frame's context, or with this bound to a node or remote object, which also awaits a returned promise or thenable. It's retried only on errors Chrome raises before the script runs, so a navigation that cuts off the await raises ExecutionContextDestroyedError. Node and RemoteObject arguments are passed by reference.
  5. Result. #evaluate converts Chrome's deep serialization into Ruby, #evaluate_handle wraps an object in a RemoteObject, and #execute returns true. A thrown value raises JavaScriptError.

For example, this call:

page.evaluate("await fetch(url).then(r => r.status)", url: "/ping")

is an expression that uses await, so it's sent as:

async function(url) {
return (
await fetch(url).then(r => r.status)
);
}

with the arguments [{ value: "/ping" }]. Chrome awaits the promise and answers with { type: "number", value: 200 }, which comes back as 200. A declaration takes positional arguments instead:

node.evaluate("function(prefix, suffix) { return prefix + this.id + suffix }", "#", "!")

is sent unchanged, with this bound to the node and the arguments ["#", "!"], and comes back as "#main!".

Constant Summary collapse

INTERMITTENT_ATTEMPTS =

Returns:

  • (Object)
ENV.fetch("FERRUM_INTERMITTENT_ATTEMPTS", 6).to_i
INTERMITTENT_SLEEP =

Returns:

  • (Object)
ENV.fetch("FERRUM_INTERMITTENT_SLEEP", 0.1).to_f
DEEP_SERIALIZATION =

Returns:

  • (::Hash[Symbol, untyped])
{
  serialization: "deep",
  additionalParameters: { maxNodeDepth: 0, includeShadowTree: "none" }
}.freeze
SHALLOW_SERIALIZATION =

Describes a primitive or node result, which a handle can't stand for, without serializing an object that stays in the browser.

Returns:

  • (::Hash[Symbol, untyped])
DEEP_SERIALIZATION.merge(maxDepth: 0).freeze
UNSERIALIZABLE_NUMBERS =

Returns:

  • (::Hash[String, Float])
{
  "NaN" => Float::NAN,
  "-0" => -0.0,
  "Infinity" => Float::INFINITY,
  "-Infinity" => -Float::INFINITY
}.freeze

Instance Method Summary collapse

Instance Method Details

#evaluate(expression, *positional, **keywords) ⇒ Object

Evaluates JavaScript and returns the result, serialized into Ruby.

Examples:

browser.evaluate("[window.scrollX, window.scrollY]") # => [0, 0]
browser.evaluate("a + b", a: 1, b: 2) # => 3
browser.evaluate("await fetch(url).then(r => r.status)", url: "/") # => 200

Parameters:

  • expression (String) —

    A JavaScript expression, or a function declaration.

  • positional (Array) —

    Arguments reachable as arguments[0] and up. Can't be combined with named ones.

  • keywords (Hash) —

    Named arguments, which become the function's parameters, plus:

Options Hash (**keywords):

  • :timeout (Numeric, nil) —

    How long to wait for the script, and any promise it returns, to settle, in seconds. Defaults to the page timeout.

Returns:

  • (Object) —

    The result. DOM nodes come back as Node, arrays and plain objects are converted recursively, and cyclic values become CyclicObject.

Raises:



198
199
200
# File 'lib/ferrum/frame/runtime.rb', line 198

def evaluate(expression, *positional, **keywords)
  run(expression, positional, keywords, mode: :value)
end

#evaluate_handle(expression, *positional, **keywords) ⇒ RemoteObject, ...

Same as #evaluate, but returns a RemoteObject that keeps the value in the browser instead of serializing it. Handles can be passed back in as arguments. Primitives are returned as-is, and DOM nodes as Node, since both are already usable from Ruby.

Examples:

list = page.evaluate_handle("document.querySelectorAll('li')")
page.evaluate("Array.from(nodes).map(n => n.textContent)", nodes: list)

Parameters:

  • expression (String) —

    A JavaScript expression, or a function declaration.

  • positional (Array) —

    Arguments reachable as arguments[0] and up. Can't be combined with named ones.

  • keywords (Hash) —

    Named arguments, which become the function's parameters, plus:

Options Hash (**keywords):

  • :timeout (Numeric, nil) —

    How long to wait for the script, and any promise it returns, to settle, in seconds. Defaults to the page timeout.

Returns:

Raises:



219
220
221
# File 'lib/ferrum/frame/runtime.rb', line 219

def evaluate_handle(expression, *positional, **keywords)
  run(expression, positional, keywords, mode: :handle)
end

#evaluate_in(object, expression, positional, keywords, mode: :value) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Backs Evaluatable#evaluate, Evaluatable#evaluate_handle and Evaluatable#execute of Node and RemoteObject. Runs the script with this bound to object, using the same argument and script conventions as #evaluate.

Parameters:

  • object (Node, RemoteObject) —

    The node or object to bind this to.

  • mode (Symbol) (defaults to: :value) —

    :value, :handle or :none.

  • expression (Object)
  • positional (::Array[untyped])
  • keywords (::Hash[::Symbol, untyped])
  • mode: (::Symbol) (defaults to: :value)

Returns:

  • (Object)

Raises:



265
266
267
# File 'lib/ferrum/frame/runtime.rb', line 265

def evaluate_in(object, expression, positional, keywords, mode: :value)
  run(expression, positional, keywords, mode: mode, on: object)
end

#execute(expression, *positional, **keywords) ⇒ nil

Runs JavaScript for its side effects and discards the result. Unlike #evaluate, the script is used as a function body rather than an expression, so multiple statements need no wrapping.

Examples:

browser.execute("window.scrollBy(0, 100)") # => true
browser.execute(<<~JS, url: "/next")
  history.pushState({}, "", url);
  window.dispatchEvent(new Event("popstate"));
JS

Parameters:

  • expression (String) —

    A JavaScript expression, or a function declaration.

  • positional (Array) —

    Arguments reachable as arguments[0] and up. Can't be combined with named ones.

  • keywords (Hash) —

    Named arguments, which become the function's parameters, plus:

Options Hash (**keywords):

  • :timeout (Numeric, nil) —

    How long to wait for the script, and any promise it returns, to settle, in seconds. Defaults to the page timeout.

Returns:

  • (nil) —

    Always true.

Raises:



243
244
245
246
# File 'lib/ferrum/frame/runtime.rb', line 243

def execute(expression, *positional, **keywords)
  run(expression, positional, keywords, mode: :none)
  nil
end