SeleniumHQ/selenium · error · RuntimeError

{fn_name}() must be called in a connection context.

Error message

{fn_name}() must be called in a connection context.

What it means

Raised as a RuntimeError by get_connection_context(fn_name) when the contextvars.ContextVar _connection_context has no value set (LookupError). The CDP module uses contextvars to implicitly pass the active connection through the call stack; CDP API functions call get_connection_context to retrieve it. If called outside a connection_context() or async with connection block, there is no current connection and the function cannot dispatch commands.

Source

Thrown at py/private/cdp.py:93

        selenium_logger.debug("Falling back to loading `devtools`: v%s", latest)
        devtools = importlib.import_module(f"{base}{latest}")
        return devtools


_connection_context: contextvars.ContextVar = contextvars.ContextVar("connection_context")
_session_context: contextvars.ContextVar = contextvars.ContextVar("session_context")


def get_connection_context(fn_name):
    """Look up the current connection.

    If there is no current connection, raise a ``RuntimeError`` with a
    helpful message.
    """
    try:
        return _connection_context.get()
    except LookupError:
        raise RuntimeError(f"{fn_name}() must be called in a connection context.")


def get_session_context(fn_name):
    """Look up the current session.

    If there is no current session, raise a ``RuntimeError`` with a
    helpful message.
    """
    try:
        return _session_context.get()
    except LookupError:
        raise RuntimeError(f"{fn_name}() must be called in a session context.")


@contextmanager
def connection_context(connection):
    """Context manager installs ``connection`` as the session context for the current Trio task."""
    token = _connection_context.set(connection)

View on GitHub (pinned to aa36b38e69)

Solutions

  1. Wrap all CDP API calls inside `async with connection:` or `with connection_context(conn):` so the ContextVar is set.
  2. If calling from a separate task or callback, explicitly re-establish the context: `with connection_context(conn):` inside that task.
  3. Pass the connection explicitly to methods that accept it rather than relying on the implicit context.

Example fix

# before
async def main():
    conn = await Connection.create(url)
    doc = await dom.get_document()  # RuntimeError: no connection context

# after
async def main():
    conn = await Connection.create(url)
    async with conn:
        doc = await dom.get_document()  # context is set
Defensive patterns

Strategy: try-catch

Validate before calling

# Ensure you are inside a connection context before calling CDP functions
from selenium.webdriver.common.bidi.cdp import get_connection_context
try:
    conn = get_connection_context('check')
except RuntimeError:
    # enter a connection context first
    pass

Try / catch

try:
    await dom.get_document()
except RuntimeError as e:
    if 'connection context' in str(e):
        async with conn:
            await dom.get_document()
    else:
        raise

Prevention

When it happens

Trigger: Calling a CDP API function that relies on get_connection_context() — such as dom.get_document() or any module-level CDP call — outside of a `with connection_context(conn):` block or outside an `async with conn:` session. The ContextVar has no default and was never set in the current context.

Common situations: Calling a CDP helper function at the wrong scope (before entering the connection context); refactoring code and moving a CDP call outside the `async with` block; using CDP functions in a callback or different task that does not inherit the contextvar; forgetting to wrap calls in the context manager.

Related errors


AI-assisted analysis of SeleniumHQ/selenium@aa36b38e69 (2026-08-14). Data as JSON: /api/errors/5b293d539eb1624e. Report an issue: GitHub.