Search by

adachsoft / web-browser-cdp

Arkadiusz Adach

Chrome DevTools Protocol implementation of adachsoft/web-browser-contract: drive a real Chrome (also Windows Chrome from WSL) - tabs, navigation, accessibility-tree snapshots with element refs, clicks, typing, forms, uploads, screenshots, JavaScript dialogs.

Package info

gitlab.com/a.adach/web-browser-cdp

Issues

pkg:composer/adachsoft/web-browser-cdp

Statistics

Installs: 13

Dependents: 0

Suggesters: 0

Stars: 0

v0.1.0 2026-11-28 11:17 UTC

This package is auto-updated.

Last update: 2026-11-28 10:18:15 UTC


README

Chrome DevTools Protocol (CDP) implementation of adachsoft/web-browser-contract: drives a real, already running Chrome / Chromium. It is built for AI agents that operate web panels "like a human": read the page as text and an accessibility tree with element refs, click, type, fill forms, upload files, take screenshots and handle JavaScript dialogs, with every operation bounded by a timeout.

Installation

Install the library with Composer:

composer require adachsoft/web-browser-cdp

Requirements

  • PHP 8.3+
  • Chrome / Chromium started with --remote-debugging-port and a dedicated --user-data-dir (Chrome 136+ ignores the debugging port for the default profile).
  • phrity/websocket (installed automatically).

Starting Chrome

Use a separate, persistent profile for the agent. Log in to the needed sites once by hand in that profile; the library never automates logins.

Linux / macOS:

google-chrome --user-data-dir="$HOME/.browser-agent-profile" --remote-debugging-port=9222 --no-first-run

Windows Chrome driven from WSL2 (verified with networkingMode=mirrored in .wslconfig):

"/mnt/c/Program Files/Google/Chrome/Application/chrome.exe" \
  --user-data-dir='C:\BrowserAgent\profile' --remote-debugging-port=9222 \
  --no-first-run --no-default-browser-check about:blank &
curl -s http://127.0.0.1:9222/json/version   # reachable from WSL directly in mirrored mode

Notes:

  • In mirrored mode Chrome's 127.0.0.1:9222 is reachable from WSL as is; the port stays bound to localhost. With the older NAT mode you would need the Windows host IP plus a netsh interface portproxy rule; prefer mirrored mode.
  • If Chrome is already running with the same profile, a new start only opens a window in the existing process (without the debugging port). Stop that instance first.
  • To stop only the agent's Chrome, match its profile directory, e.g. in PowerShell: Get-CimInstance Win32_Process -Filter "Name='chrome.exe'" | ? CommandLine -like '*BrowserAgent*' | % { Stop-Process -Id $_.ProcessId }.

Usage

use AdachSoft\WebBrowserCdp\Browser\CdpBrowserConfigDto;
use AdachSoft\WebBrowserCdp\Browser\CdpWebBrowserFactory;
use AdachSoft\WebBrowserContract\Collections\SelectOptionVoCollection;
use AdachSoft\WebBrowserContract\Dto\ScreenshotOptionsDto;
use AdachSoft\WebBrowserContract\Dto\WaitConditionDto;
use AdachSoft\WebBrowserContract\ValueObjects\SelectOptionVo;
use AdachSoft\WebBrowserContract\ValueObjects\UrlVo;

$browser = (new CdpWebBrowserFactory())->create(new CdpBrowserConfigDto(
    endpoint: 'http://127.0.0.1:9222',
    defaultTimeoutMs: 30_000,
));

$tab = $browser->openTab(new UrlVo('https://example.com/form'));   // new tab owned by this session
$page = $tab->readPage();
echo $page->accessibilityTree;
// - document "Form" [ref=e1.3fa2]
//   - textbox "Name" [value=""] [ref=e12.3fa2]
//   - combobox "Country" [value="--"] [ref=e15.3fa2]
//   - button "Save draft" [ref=e20.3fa2]

$tab->type($page->elements[1]->ref, 'Arek');
$tab->selectOptions($page->elements[2]->ref, new SelectOptionVoCollection([new SelectOptionVo('Poland')]));
$result = $tab->click($page->elements[3]->ref);       // ActionResultDto: navigated, new tab, dialog, URLs
$tab->waitFor(WaitConditionDto::forText('Saved'));
$png = $tab->screenshot(new ScreenshotOptionsDto(fullPage: true, maxWidth: 1280));
$browser->closeTab($tab->getTabId());                 // only tabs opened by the session can be closed

Element refs

Refs look like e<backendNodeId>.<document key>. They are stateless: the CDP backendNodeId is valid in any CDP session, so a ref from readPage() can be used by a later PHP process. The document key (derived from the main frame's loader id) makes refs from a previous page fail with StaleElementReferenceException instead of hitting a different element.

Actions

  • click scrolls the element into view, checks that it is enabled and not covered by another element (hit test at the click point), then dispatches real mouse events.
  • type focuses the field, optionally clears it (select all + Backspace) and inserts the text (Input.insertText).
  • selectOptions works on native <select> elements; custom listboxes are operated with click.
  • setChecked clicks checkboxes / radios / switches (ARIA too) only when the state differs; styled checkboxes with a hidden native input fall back to a DOM click.
  • uploadFiles uses DOM.setFileInputFiles; when Chrome reports File-Path-Style: windows and PHP does not run on Windows (WSL), paths are translated: /mnt/d/x -> D:\x, other paths via wslpath -w.
  • Every action returns ActionResultDto (URL before/after, navigation, popup tab id, dialog opened / handled). Popups opened by an action become owned by the session.
  • With CdpBrowserConfigDto::$irreversibleActionPolicy set, every action (and accepting a dialog) is checked by IrreversibleActionGuard; the target element (role + accessible name) is read live from the accessibility tree.

State between processes

Tab ownership and seen JavaScript dialogs are stored in a JSON state file (default <sys temp>/web-browser-cdp/state-<endpoint hash>.json, configurable with stateFilePath), guarded by flock.

JavaScript dialogs

CDP lets only the session that had the Page domain enabled when a dialog opened answer it (Page.handleJavaScriptDialog); a new connection gets "No dialog is showing" and Page.enable blocks until the dialog is closed. Therefore:

  • Recommended: give the answer with the action - ActionOptionsDto::$dialogResponse (DialogResponseDto::accept(promptText, expectedMessage) / DialogResponseDto::dismiss(expectedMessage)). A dialog opened by the action is answered in the same session and reported in ActionResultDto::$handledDialog / $dialogAction. With expectedMessage it is answered only when its message contains that text; otherwise it stays pending (ActionResultDto::hasPendingDialog()). Accepting goes through the irreversible-action guard (DIALOG_ACCEPT, consent from the same options); without consent the action has already run, the dialog stays open and IrreversibleActionNotConfirmedException is thrown.

    $result = $tab->click($deleteRef, new ActionOptionsDto(
        irreversibleConsent: new IrreversibleConsentVo('task1301_c7: delete draft'),
        dialogResponse: DialogResponseDto::accept(expectedMessage: 'Really delete'),
    ));
    
  • within one CdpWebBrowser instance (one process) getPendingDialog() / handleDialog() also work;

  • in a later process the tab is detected as blocked (Page.enable probe, pageEnableProbeMs), getPendingDialog() returns the stored dialog (type + message) and every action fails with a clear message, but handleDialog() throws BrowserOperationFailedException - the user has to close the dialog in Chrome (or the tab is closed).
  • beforeunload dialogs during openUrl() are not answered automatically (navigation fails with a message).

Known limitations

  • Cross-origin iframes (out-of-process frames) are not included in the accessibility tree and their elements cannot be addressed yet.
  • type() inserts text with Input.insertText (one input event, no per-character key events); widgets that react only to key events may need pressKey().
  • TabInfoDto::$active is always false (CDP does not report the focused tab cheaply).

Tests

composer test                       # unit tests (fake CDP transport)
CDP_URL=http://127.0.0.1:9222 composer test:integration   # real Chrome, local fixture pages served by php -S
composer stan
composer cs:check

The integration tests open and close their own tabs only and use local fixture pages; never point them at a profile with real accounts.

License

MIT