adachsoft / web-browser-cdp
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.
Requires
- php: ^8.3
- adachsoft/web-browser-contract: ^0.1
- phrity/websocket: ^4.1
Requires (Dev)
- adachsoft/php-code-style: ^0.8.0
- friendsofphp/php-cs-fixer: ^3.95
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13
- rector/rector: ^2.9
- symplify/phpstan-rules: ^14.19
Suggests
None
Provides
None
Conflicts
None
Replaces
None
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-portand 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:9222is reachable from WSL as is; the port stays bound to localhost. With the older NAT mode you would need the Windows host IP plus anetsh interface portproxyrule; 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
clickscrolls 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.typefocuses the field, optionally clears it (select all + Backspace) and inserts the text (Input.insertText).selectOptionsworks on native<select>elements; custom listboxes are operated withclick.setCheckedclicks checkboxes / radios / switches (ARIA too) only when the state differs; styled checkboxes with a hidden native input fall back to a DOM click.uploadFilesusesDOM.setFileInputFiles; when Chrome reportsFile-Path-Style: windowsand PHP does not run on Windows (WSL), paths are translated:/mnt/d/x->D:\x, other paths viawslpath -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::$irreversibleActionPolicyset, every action (and accepting a dialog) is checked byIrreversibleActionGuard; 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 inActionResultDto::$handledDialog/$dialogAction. WithexpectedMessageit 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 andIrreversibleActionNotConfirmedExceptionis thrown.$result = $tab->click($deleteRef, new ActionOptionsDto( irreversibleConsent: new IrreversibleConsentVo('task1301_c7: delete draft'), dialogResponse: DialogResponseDto::accept(expectedMessage: 'Really delete'), ));within one
CdpWebBrowserinstance (one process)getPendingDialog()/handleDialog()also work;- in a later process the tab is detected as blocked (
Page.enableprobe,pageEnableProbeMs),getPendingDialog()returns the stored dialog (type + message) and every action fails with a clear message, buthandleDialog()throwsBrowserOperationFailedException- the user has to close the dialog in Chrome (or the tab is closed). beforeunloaddialogs duringopenUrl()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 withInput.insertText(one input event, no per-character key events); widgets that react only to key events may needpressKey().TabInfoDto::$activeis alwaysfalse(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