> ## Documentation Index
> Fetch the complete documentation index at: https://docs.mobilerun.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Execute JavaScript in the device's Chrome browser (CDP)

> Evaluates a JavaScript expression exactly once in the device's single, confirmed foreground Chrome tab via the Chrome DevTools Protocol and returns its JSON-serialized result. A responsive browser state without exactly one visible page returns DEVICE_NO_BROWSER_TARGET (400). Transient discovery, page-dial, or visibility-probe transport failures return CDP_TRANSPORT_UNAVAILABLE (503) with Retry-After and an executionOutcome; the service may start Chrome once and retry selection before Runtime.evaluate, but dial or probe recovery is skipped for a backgrounded Chrome, and a user script is never retried after its write or read. Devices without browser support return an unsupported-feature error.

The script is a single JavaScript expression, not a function body — skip the top-level `return` and wrap multi-statement logic in an IIFE:

```js
(() => { const links = [...document.querySelectorAll('a')]; return links.map(a => a.href); })()
```

The result must be JSON-serializable: `undefined` comes back as `null`, and `NaN`, `Infinity`, and `-0` are returned as strings. Scripts run in Chrome itself — in-app WebViews are not reachable. iOS devices don't support browser control and fail with `400`.

If CDP discovery, page connection, or the foreground visibility probe fails before `Runtime.evaluate` is sent, the service may start Chrome once and retry target selection. Dial and probe recovery only starts Chrome when it is already the foreground app (or the Chrome CDP socket itself is unavailable), so a backgrounded browser still fails closed. The response keeps the `CDP_TRANSPORT_UNAVAILABLE` `503` contract and reports the phase and recovery result in its details when recovery was attempted. A selection deadline shortfall, or failures while writing or reading `Runtime.evaluate`, is never replayed.

> [!TIP]
>
> For a persistent session or full DevTools protocol access, connect a Playwright- or Puppeteer-style CDP client to the raw websocket at `/devices/{deviceId}/browser/cdp` instead of issuing one-shot calls.


## OpenAPI

````yaml /api-reference/phones/browser.yaml post /devices/{deviceId}/browser/execute-script
openapi: 3.1.0
info:
  title: Browser
  version: v1
servers:
  - description: Droidrun Cloud API
    url: https://api.mobilerun.ai/v1
security:
  - bearerAuth: []
paths:
  /devices/{deviceId}/browser/execute-script:
    post:
      tags:
        - Browser
      summary: Execute JavaScript in the device's Chrome browser (CDP)
      description: >-
        Evaluates a JavaScript expression exactly once in the device's single,
        confirmed foreground Chrome tab via the Chrome DevTools Protocol and
        returns its JSON-serialized result. A responsive browser state without
        exactly one visible page returns DEVICE_NO_BROWSER_TARGET (400).
        Transient discovery, page-dial, or visibility-probe transport failures
        return CDP_TRANSPORT_UNAVAILABLE (503) with Retry-After and an
        executionOutcome; the service may start Chrome once and retry selection
        before Runtime.evaluate, but dial or probe recovery is skipped for a
        backgrounded Chrome, and a user script is never retried after its write
        or read. Devices without browser support return an unsupported-feature
        error.
      operationId: browser-execute-script
      parameters:
        - in: path
          name: deviceId
          required: true
          schema:
            type: string
        - in: header
          name: X-Device-Display-ID
          schema:
            default: 0
            format: int64
            minimum: 0
            type: integer
      requestBody:
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/ExecuteScriptArgs'
        required: true
      responses:
        '200':
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ExecuteScriptOutputBody'
          description: OK
        default:
          content:
            application/problem+json:
              schema:
                $ref: '#/components/schemas/ErrorModel'
          description: Error
      x-codeSamples:
        - lang: JavaScript
          source: >-
            import Mobilerun from '@mobilerun/sdk';


            const client = new Mobilerun({
              apiKey: process.env['MOBILERUN_CLOUD_API_KEY'], // This is the default and can be omitted
            });


            const response = await
            client.devices.browser.executeScript('deviceId', { script: 'script'
            });


            console.log(response.result);
        - lang: Python
          source: |-
            import os
            from mobilerun_sdk import Mobilerun

            client = Mobilerun(
                api_key=os.environ.get("MOBILERUN_CLOUD_API_KEY"),  # This is the default and can be omitted
            )
            response = client.devices.browser.execute_script(
                device_id="deviceId",
                script="script",
            )
            print(response.result)
components:
  schemas:
    ExecuteScriptArgs:
      additionalProperties: false
      properties:
        $schema:
          description: A URL to the JSON Schema for this object.
          examples:
            - https://example.com/schemas/ExecuteScriptArgs.json
          format: uri
          readOnly: true
          type: string
        script:
          description: >-
            JavaScript expression to evaluate in the device's foreground Chrome
            tab (CDP Runtime.evaluate). It is an expression, not a function body
            — the expression's value is returned (no top-level 'return'). Must
            evaluate to a JSON-serializable value; wrap multi-statement logic in
            an IIFE, e.g. (() => { ... ; return x })().
          type: string
      required:
        - script
      type: object
    ExecuteScriptOutputBody:
      additionalProperties: false
      properties:
        $schema:
          description: A URL to the JSON Schema for this object.
          examples:
            - https://example.com/schemas/ExecuteScriptOutputBody.json
          format: uri
          readOnly: true
          type: string
        result:
          description: >-
            JSON-serialized return value of the script (null if it returned
            undefined). Non-JSON-serializable numbers (Infinity, NaN, -0) are
            returned as their string representation.
      required:
        - result
      type: object
    ErrorModel:
      additionalProperties: false
      properties:
        $schema:
          description: A URL to the JSON Schema for this object.
          examples:
            - https://example.com/schemas/ErrorModel.json
          format: uri
          readOnly: true
          type: string
        detail:
          description: >-
            A human-readable explanation specific to this occurrence of the
            problem.
          examples:
            - Property foo is required but is missing.
          type: string
        errors:
          description: Optional list of individual error details
          items:
            $ref: '#/components/schemas/ErrorDetail'
          type:
            - array
            - 'null'
        instance:
          description: >-
            A URI reference that identifies the specific occurrence of the
            problem.
          examples:
            - https://example.com/error-log/abc123
          format: uri
          type: string
        status:
          description: HTTP status code
          examples:
            - 400
          format: int64
          type: integer
        title:
          description: >-
            A short, human-readable summary of the problem type. This value
            should not change between occurrences of the error.
          examples:
            - Bad Request
          type: string
        type:
          default: about:blank
          description: A URI reference to human-readable documentation for the error.
          examples:
            - https://example.com/errors/example
          format: uri
          type: string
      type: object
    ErrorDetail:
      additionalProperties: false
      properties:
        location:
          description: >-
            Where the error occurred, e.g. 'body.items[3].tags' or
            'path.thing-id'
          type: string
        message:
          description: Error message text
          type: string
        value:
          description: The value at the given location
      type: object
  securitySchemes:
    bearerAuth:
      bearerFormat: Opaque
      description: Bearer token via Authorization header
      scheme: bearer
      type: http

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.