跳转至

运行时命令

运行时命令提供 JavaScript 执行功能和运行时环境管理。

概述

运行时命令模块支持在浏览器上下文中执行 JavaScript 代码、检查对象以及控制运行时环境。

pydoll.commands.runtime_commands

RuntimeCommands

A class for interacting with the JavaScript runtime using Chrome DevTools Protocol.

This class provides methods to create commands for evaluating JavaScript expressions, calling functions on JavaScript objects, and retrieving object properties through CDP.

ATTRIBUTE DESCRIPTION
EVALUATE_TEMPLATE

Template for the Runtime.evaluate command.

TYPE: dict

CALL_FUNCTION_ON_TEMPLATE

Template for the Runtime.callFunctionOn command.

TYPE: dict

GET_PROPERTIES

Template for the Runtime.getProperties command.

TYPE: dict

add_binding staticmethod

add_binding(name, execution_context_name=None)

Creates a command to add a JavaScript binding.

PARAMETER DESCRIPTION
name

Name of the binding to add.

TYPE: str

execution_context_name

Name of the execution context to bind to.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to add a JavaScript binding.

await_promise staticmethod

await_promise(promise_object_id, return_by_value=None, generate_preview=None)

Creates a command to await a JavaScript promise and return its result.

PARAMETER DESCRIPTION
promise_object_id

ID of the promise to await.

TYPE: str

return_by_value

Whether to return the result by value instead of reference.

TYPE: Optional[bool] DEFAULT: None

generate_preview

Whether to generate a preview for the result.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Command[AwaitPromiseResponse]

Command[AwaitPromiseResponse]: Command object to await a promise.

call_function_on staticmethod

call_function_on(function_declaration, object_id=None, arguments=None, silent=None, return_by_value=None, generate_preview=None, user_gesture=None, await_promise=None, execution_context_id=None, object_group=None, throw_on_side_effect=None, unique_context_id=None, serialization_options=None)

Creates a command to call a function with a given declaration on a specific object.

PARAMETER DESCRIPTION
function_declaration

Declaration of the function to call.

TYPE: str

object_id

ID of the object to call the function on.

TYPE: Optional[str] DEFAULT: None

arguments

Arguments to pass to the function.

TYPE: Optional[list[CallArgument]] DEFAULT: None

silent

Whether to silence exceptions.

TYPE: Optional[bool] DEFAULT: None

return_by_value

Whether to return the result by value instead of reference.

TYPE: Optional[bool] DEFAULT: None

generate_preview

Whether to generate a preview for the result.

TYPE: Optional[bool] DEFAULT: None

user_gesture

Whether to treat the call as initiated by user gesture.

TYPE: Optional[bool] DEFAULT: None

await_promise

Whether to await promise result.

TYPE: Optional[bool] DEFAULT: None

execution_context_id

ID of the execution context to call the function in.

TYPE: Optional[str] DEFAULT: None

object_group

Symbolic group name for the result.

TYPE: Optional[str] DEFAULT: None

throw_on_side_effect

Whether to throw if side effect cannot be ruled out.

TYPE: Optional[bool] DEFAULT: None

unique_context_id

Unique context ID for the function call.

TYPE: Optional[str] DEFAULT: None

serialization_options

Serialization options for the result.

TYPE: Optional[SerializationOptions] DEFAULT: None

RETURNS DESCRIPTION
Command[CallFunctionOnResponse]

Command[CallFunctionOnResponse]: Command object to call a function on an object.

compile_script staticmethod

compile_script(expression, source_url=None, persist_script=None, execution_context_id=None)

Creates a command to compile a JavaScript expression.

PARAMETER DESCRIPTION
expression

JavaScript expression to compile.

TYPE: str

source_url

URL of the source file for the script.

TYPE: Optional[str] DEFAULT: None

persist_script

Whether to persist the compiled script.

TYPE: Optional[bool] DEFAULT: None

execution_context_id

ID of the execution context to compile the script in.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Command[CompileScriptResponse]

Command[CompileScriptResponse]: Command object to compile a script.

disable staticmethod

disable()

Disables the runtime domain.

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to disable the runtime domain.

enable staticmethod

enable()

Enables the runtime domain.

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to enable the runtime domain.

evaluate staticmethod

evaluate(expression, object_group=None, include_command_line_api=None, silent=None, context_id=None, return_by_value=None, generate_preview=None, user_gesture=None, await_promise=None, throw_on_side_effect=None, timeout=None, disable_breaks=None, repl_mode=None, allow_unsafe_eval_blocked_by_csp=None, unique_context_id=None, serialization_options=None)

Creates a command to evaluate a JavaScript expression in the global context.

PARAMETER DESCRIPTION
expression

JavaScript expression to evaluate.

TYPE: str

object_group

Symbolic group name for the result.

TYPE: Optional[str] DEFAULT: None

include_command_line_api

Whether to include command line API.

TYPE: Optional[bool] DEFAULT: None

silent

Whether to silence exceptions.

TYPE: Optional[bool] DEFAULT: None

context_id

ID of the execution context to evaluate in.

TYPE: Optional[str] DEFAULT: None

return_by_value

Whether to return the result by value instead of reference.

TYPE: Optional[bool] DEFAULT: None

generate_preview

Whether to generate a preview for the result.

TYPE: Optional[bool] DEFAULT: None

user_gesture

Whether to treat evaluation as initiated by user gesture.

TYPE: Optional[bool] DEFAULT: None

await_promise

Whether to await promise result.

TYPE: Optional[bool] DEFAULT: None

throw_on_side_effect

Whether to throw if side effect cannot be ruled out.

TYPE: Optional[bool] DEFAULT: None

timeout

Timeout in milliseconds.

TYPE: Optional[float] DEFAULT: None

disable_breaks

Whether to disable breakpoints during evaluation.

TYPE: Optional[bool] DEFAULT: None

repl_mode

Whether to execute in REPL mode.

TYPE: Optional[bool] DEFAULT: None

allow_unsafe_eval_blocked_by_csp

Allow unsafe evaluation.

TYPE: Optional[bool] DEFAULT: None

unique_context_id

Unique context ID for evaluation.

TYPE: Optional[str] DEFAULT: None

serialization_options

Serialization for the result.

TYPE: Optional[SerializationOptions] DEFAULT: None

RETURNS DESCRIPTION
Command[EvaluateResponse]

Command[EvaluateResponse]: Command object to evaluate JavaScript.

get_properties staticmethod

get_properties(object_id, own_properties=None, accessor_properties_only=None, generate_preview=None, non_indexed_properties_only=None)

Creates a command to get properties of a JavaScript object.

PARAMETER DESCRIPTION
object_id

ID of the object to get properties for.

TYPE: str

own_properties

Whether to return only own properties.

TYPE: Optional[bool] DEFAULT: None

accessor_properties_only

Whether to return only accessor properties.

TYPE: Optional[bool] DEFAULT: None

generate_preview

Whether to generate previews for property values.

TYPE: Optional[bool] DEFAULT: None

non_indexed_properties_only

Whether to return only non-indexed properties.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Command[GetPropertiesResponse]

Command[GetPropertiesResponse]: Command object to get object properties.

global_lexical_scope_names staticmethod

global_lexical_scope_names(execution_context_id=None)

Creates a command to retrieve names of variables from global lexical scope.

PARAMETER DESCRIPTION
execution_context_id

ID of the execution context to get scope names from.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Command[GlobalLexicalScopeNamesResponse]

Command[GlobalLexicalScopeNamesResponse]: Command object to get global lexical scope names.

query_objects staticmethod

query_objects(prototype_object_id, object_group=None)

Creates a command to query objects with a given prototype.

PARAMETER DESCRIPTION
prototype_object_id

ID of the prototype object.

TYPE: str

object_group

Symbolic group name for the results.

TYPE: Optional[str] DEFAULT: None

RETURNS DESCRIPTION
Command[QueryObjectsResponse]

Command[QueryObjectsResponse]: Command object to query objects.

release_object staticmethod

release_object(object_id)

Creates a command to release a JavaScript object.

PARAMETER DESCRIPTION
object_id

ID of the object to release.

TYPE: str

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to release an object.

release_object_group staticmethod

release_object_group(object_group)

Creates a command to release all objects in a group.

PARAMETER DESCRIPTION
object_group

Name of the object group to release.

TYPE: str

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to release an object group.

remove_binding staticmethod

remove_binding(name)

Creates a command to remove a JavaScript binding.

PARAMETER DESCRIPTION
name

Name of the binding to remove.

TYPE: str

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to remove a JavaScript binding.

run_script staticmethod

run_script(script_id, execution_context_id=None, object_group=None, silent=None, include_command_line_api=None, return_by_value=None, generate_preview=None, await_promise=None)

Creates a command to run a compiled script.

PARAMETER DESCRIPTION
script_id

ID of the compiled script to run.

TYPE: str

execution_context_id

ID of the execution context to run the script in.

TYPE: Optional[str] DEFAULT: None

object_group

Symbolic group name for the result.

TYPE: Optional[str] DEFAULT: None

silent

Whether to silence exceptions.

TYPE: Optional[bool] DEFAULT: None

include_command_line_api

Whether to include command line API.

TYPE: Optional[bool] DEFAULT: None

return_by_value

Whether to return the result by value instead of reference.

TYPE: Optional[bool] DEFAULT: None

generate_preview

Whether to generate a preview for the result.

TYPE: Optional[bool] DEFAULT: None

await_promise

Whether to await promise result.

TYPE: Optional[bool] DEFAULT: None

RETURNS DESCRIPTION
Command[RunScriptResponse]

Command[RunScriptResponse]: Command object to run a script.

set_async_call_stack_depth staticmethod

set_async_call_stack_depth(max_depth)

Creates a command to set the async call stack depth.

PARAMETER DESCRIPTION
max_depth

Maximum depth of async call stacks.

TYPE: int

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to set async call stack depth.

set_custom_object_formatter_enabled staticmethod

set_custom_object_formatter_enabled(enabled)

Creates a command to enable or disable custom object formatters.

PARAMETER DESCRIPTION
enabled

Whether to enable custom object formatters.

TYPE: bool

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to enable/disable custom object formatters.

set_max_call_stack_size_to_capture staticmethod

set_max_call_stack_size_to_capture(size)

Creates a command to set the maximum call stack size to capture.

PARAMETER DESCRIPTION
size

Maximum call stack size to capture.

TYPE: int

RETURNS DESCRIPTION
Command[Response]

Command[Response]: Command object to set max call stack size.

用法

运行时命令用于 JavaScript 执行和运行时管理:

from pydoll.commands.runtime_commands import evaluate, enable
from pydoll.connection.connection_handler import ConnectionHandler

# Enable runtime events
connection = ConnectionHandler()
await enable(connection)

# Execute JavaScript
result = await evaluate(
    connection, 
    expression="document.title",
    return_by_value=True
)
print(result.value)  # Page title

主要功能

运行时命令模块提供以下功能:

JavaScript 执行

  • evaluate() - 执行 JavaScript 表达式
  • call_function_on() - 调用对象上的函数
  • compile_script() - 编译 JavaScript 以供复用
  • run_script() - 运行已编译的脚本

对象管理

  • get_properties() - 获取对象属性
  • release_object() - 释放对象引用
  • release_object_group() - 释放对象组

运行时控制

  • enable() / disable() - 启用/禁用运行时事件
  • discard_console_entries() - 清除控制台记录
  • set_custom_object_formatter_enabled() - 启用自定义格式化程序

异常处理

  • set_async_call_stack_depth() - 设置调用堆栈深度
  • 异常捕获和报告
  • 错误对象检查

高级用法

复杂的 JavaScript 执行

# 执行带有错误处理的复杂 JavaScript
script = """
try {
    const elements = document.querySelectorAll('.item');
    return Array.from(elements).map(el => ({
        text: el.textContent,
        href: el.href
    }));
} catch (error) {
    return { error: error.message };
}
"""

result = await evaluate(
    connection,
    expression=script,
    return_by_value=True,
    await_promise=True
)

对象检查

# Get detailed object properties
properties = await get_properties(
    connection,
    object_id=object_id,
    own_properties=True,
    accessor_properties_only=False
)

for prop in properties:
    print(f"{prop.name}: {prop.value}")

控制台集成

运行时命令与浏览器控制台集成: - 控制台消息和错误 - 控制台 API 方法调用 - 自定义控制台格式化程序

Performance Considerations

JavaScript execution through runtime commands can be slower than native browser execution. Use judiciously for complex operations.