Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Getgauge Taiko RuntimeHandler

From Leeroopedia
Revision as of 11:18, 16 February 2026 by Admin (talk | contribs) (Auto-imported from implementations/Getgauge_Taiko_RuntimeHandler.md)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Knowledge Sources
Domains Browser_Automation, Runtime_Execution
Last Updated 2026-02-12 03:00 GMT

Overview

The RuntimeHandler module manages JavaScript execution across multiple browser execution contexts (including iframes) via the Chrome DevTools Protocol Runtime domain, providing the core mechanism for evaluating expressions and finding DOM elements.

Description

RuntimeHandler is the bridge between Taiko's element-finding logic and the browser's JavaScript runtime. It maintains an array of active execution context IDs and provides three main capabilities: evaluating arbitrary JavaScript expressions, calling named functions stored on the window object, and finding elements across all execution contexts.

The module listens for the createdSession event to obtain the Runtime domain client. Upon session creation, it enables the Runtime domain and registers listeners for three execution context lifecycle events: executionContextCreated (adds new context IDs), executionContextDestroyed (removes invalidated context IDs), and executionContextsCleared (resets the entire list). This lifecycle tracking is essential because each iframe in a page creates its own execution context, and Taiko must search all of them when locating elements.

A key design pattern in runtimeCallFunctionOn is the window-function caching strategy: when calling a function in a specific execution context, the function is stored on the window object as window["taiko_" + funcName]. If the cached function is missing (detected by a TypeError), the handler automatically re-registers it before retrying the call. This avoids re-transmitting large function bodies on every call.

Usage

Use RuntimeHandler whenever Taiko needs to execute JavaScript in the browser or find elements matching a selector. The findElements function is the primary entry point used by all selector types (text, CSS, XPath, proximity selectors) to resolve element references. runtimeEvaluate and runtimeCallFunctionOn are used for more general JavaScript evaluation needs such as reading element properties, scrolling, or evaluating custom user expressions.

Code Reference

Source Location

Signature

async function findElements(exp, arg) -> Array<string>
async function runtimeEvaluate(exp, executionContextId, opt) -> RuntimeResult
async function runtimeCallFunctionOn(exp, executionContextId, opt) -> RuntimeResult

Import

const {
  findElements,
  runtimeEvaluate,
  runtimeCallFunctionOn,
} = require("./handlers/runtimeHandler");

I/O Contract

findElements(exp, arg)

Parameter Type Description
exp Function If a string, evaluated as a JavaScript expression via runtimeEvaluate. If a function, called via runtimeCallFunctionOn.
arg any Argument passed to the function when exp is a Function. Ignored when exp is a string.
Return Type Description
objectIds Array<string> Array of CDP object IDs for all matching DOM elements across all execution contexts.

runtimeEvaluate(exp, executionContextId, opt)

Parameter Type Description
exp string JavaScript expression to evaluate.
executionContextId null Execution context ID. If null/undefined, evaluates in the default context.
opt Object Options object. Supports opt.returnByValue (boolean) to return primitive values instead of object references.
Return Type Description
RuntimeResult undefined CDP Runtime.evaluate result containing result and optionally exceptionDetails. Returns undefined if the context was invalidated.

runtimeCallFunctionOn(exp, executionContextId, opt)

Parameter Type Description
exp Function JavaScript function to call. Its .name property is used for window-object caching.
executionContextId null Execution context ID. When provided, uses the window-function wrapper pattern.
opt Object Options: opt.arg (value passed to the function), opt.objectId (CDP object to call the function on), opt.returnByValue (boolean).
Return Type Description
RuntimeResult undefined CDP Runtime.callFunctionOn result. Returns undefined if the context was invalidated.

Algorithm

Element Finding Across Contexts

The findElements function iterates over all tracked execution context IDs and evaluates the given expression in each one. Results are aggregated into a single array of object IDs. This ensures elements inside iframes are discoverable alongside elements in the main frame.

for (const contextId of executionContextIds) {
  const objectIdsFromRes = await getObjectIdsFromResult(
    await evalFunc(exp, contextId, { arg: arg }),
  );
  objectIds = objectIds.concat(objectIdsFromRes);
}

Window Function Caching

When runtimeCallFunctionOn is called with a specific execution context ID, it wraps the function invocation in a pattern that looks up the function on the window object:

function expWindowWrapper(arg) {
  return window[`taiko_${arg.funcName}`](arg.arg);
}

If the function is not found (resulting in a TypeError), the handler automatically registers it:

await runtimeEvaluate(`window['taiko_${exp.name}'] = ${exp}`, executionContextId);

Then retries the call. This minimizes repeated transmission of function source code across the CDP connection.

Object ID Extraction

The getObjectIdsFromResult helper handles three cases:

  1. Single node result -- If result.subtype === "node", returns the single objectId directly.
  2. NodeList result -- Uses Runtime.getProperties to iterate numeric-keyed properties and extract each element's objectId.
  3. Undefined/error result -- Returns an empty array, unless the error indicates an invalid query function (which throws).

Context Invalidation Handling

When a CDP call fails with "Cannot find context with specified id", the handler removes that context ID from the tracked list rather than throwing. This gracefully handles scenarios where iframes are removed or pages navigate while element finding is in progress.

CDP Domain

This handler uses the Runtime domain with the following commands and events:

  • Runtime.enable -- Enables Runtime domain notifications.
  • Runtime.evaluate -- Evaluates a JavaScript expression in a specified execution context.
  • Runtime.callFunctionOn -- Calls a function on a specific object or in a specific execution context.
  • Runtime.getProperties -- Retrieves properties of an object (used to extract NodeList elements).
  • Runtime.executionContextCreated (event) -- Fired when a new execution context is created.
  • Runtime.executionContextDestroyed (event) -- Fired when an execution context is destroyed.
  • Runtime.executionContextsCleared (event) -- Fired when all execution contexts are cleared (e.g., page navigation).

Usage Examples

// Find all elements matching a CSS selector across all frames
const { findElements } = require("./handlers/runtimeHandler");
const objectIds = await findElements(
  "document.querySelectorAll('button.submit')"
);
// objectIds => ["objectId-1", "objectId-2"]

// Evaluate a JavaScript expression in the default context
const { runtimeEvaluate } = require("./handlers/runtimeHandler");
const result = await runtimeEvaluate(
  "document.title",
  null,
  { returnByValue: true }
);
// result.result.value => "My Page Title"

// Call a named function with arguments across execution contexts
const { runtimeCallFunctionOn } = require("./handlers/runtimeHandler");
function getTextContent(selector) {
  return document.querySelector(selector)?.textContent;
}
const result = await runtimeCallFunctionOn(
  getTextContent,
  contextId,
  { arg: ".header" }
);

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment