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:
- #evaluate returns the value, serialized into Ruby.
- #evaluate_handle returns a RemoteObject that stays in the browser.
- #execute discards the value and returns
true.
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.
- 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. - 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. - Wrap. A declaration is sent as it is. An expression becomes
function(<names>) { return (<code>) },asyncwhen it usesawait. Of several statements, only the last is returned, as infunction() { a(); return (b) }. #execute uses the script as written as the function body instead. - Call. One
Runtime.callFunctionOnin the frame's context, or withthisbound 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. - 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 =
ENV.fetch("FERRUM_INTERMITTENT_ATTEMPTS", 6).to_i
- INTERMITTENT_SLEEP =
ENV.fetch("FERRUM_INTERMITTENT_SLEEP", 0.1).to_f
- DEEP_SERIALIZATION =
{ 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.
DEEP_SERIALIZATION.merge(maxDepth: 0).freeze
- UNSERIALIZABLE_NUMBERS =
{ "NaN" => Float::NAN, "-0" => -0.0, "Infinity" => Float::INFINITY, "-Infinity" => -Float::INFINITY }.freeze
Instance Method Summary collapse
-
#evaluate(expression, *positional, **keywords) ⇒ Object
Evaluates JavaScript and returns the result, serialized into Ruby.
-
#evaluate_handle(expression, *positional, **keywords) ⇒ RemoteObject, ...
Same as #evaluate, but returns a RemoteObject that keeps the value in the browser instead of serializing it.
-
#evaluate_in(object, expression, positional, keywords, mode: :value) ⇒ Object
private
Backs Evaluatable#evaluate, Evaluatable#evaluate_handle and Evaluatable#execute of Node and RemoteObject.
-
#execute(expression, *positional, **keywords) ⇒ nil
Runs JavaScript for its side effects and discards the result.
Instance Method Details
#evaluate(expression, *positional, **keywords) ⇒ Object
Evaluates JavaScript and returns the result, serialized into Ruby.
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.
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.
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.
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 |