turbo-browser-mcp 0.0.0-stage → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +386 -2
- package/package.json +40 -4
- package/server.json +20 -0
- package/src/aftermath.mjs +42 -0
- package/src/browser-manager.mjs +1418 -0
- package/src/cdp-bridge.mjs +637 -0
- package/src/dom-engine.mjs +6541 -0
- package/src/guards.mjs +294 -0
- package/src/index.mjs +1212 -0
- package/src/playwright-loader.mjs +320 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Trung Thanh Tran
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,387 @@
|
|
|
1
|
-
#
|
|
1
|
+
# turbo-browser-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/Tthanh2k6/turbo-browser-mcp/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/turbo-browser-mcp)
|
|
5
|
+

|
|
6
|
+

|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
An MCP server for browser automation, built on Playwright. It has 11 tools where `@playwright/mcp` has 25 and `chrome-devtools-mcp` has 33, and each tool does more per call:
|
|
10
|
+
|
|
11
|
+
- one `smart_fill_form` call fills a whole form, including React inputs, selects, comboboxes, rich-text editors and file uploads read from disk;
|
|
12
|
+
- `inspect_compact` can return only the elements that changed since the last snapshot;
|
|
13
|
+
- `batch_actions` runs a list of clicks, key presses and form steps as one call.
|
|
14
|
+
|
|
15
|
+
Fewer calls means fewer model turns and less page text replayed in the conversation. The numbers are in [Benchmarks](#benchmarks).
|
|
16
|
+
|
|
17
|
+
Buttons that look like a final commit (Submit, Send, Publish, Pay, Confirm, and their Korean, Japanese, Chinese and Vietnamese equivalents) are blocked by default, so an agent can prefill a form and leave the last click to a person. Pass `allowSubmit: true` per call or start with `--allow-submit` to turn this off.
|
|
18
|
+
|
|
19
|
+
The server does not hide that the browser is automated: no stealth patches, no fingerprint changes, no CAPTCHA solving. For sites with a bot check it can hand the tab to a person and continue afterwards ([`wait_for_human`](#handing-a-step-to-a-person-wait_for_human---open-profile)).
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
Needs Node 20 or newer and a Chromium-based browser (Chrome, Edge, Brave, or Playwright's Chromium).
|
|
24
|
+
|
|
25
|
+
Claude Code:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
claude mcp add turbo-browser -- npx -y turbo-browser-mcp
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Clients that read an `mcpServers` JSON config (Cursor, Claude Desktop, Antigravity and others):
|
|
32
|
+
|
|
33
|
+
```json
|
|
34
|
+
{
|
|
35
|
+
"mcpServers": {
|
|
36
|
+
"turbo-browser": {
|
|
37
|
+
"command": "npx",
|
|
38
|
+
"args": ["-y", "turbo-browser-mcp"],
|
|
39
|
+
"env": { "TURBO_BROWSER_SAVE_ROOT": "/absolute/path/to/workspace" }
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
`TURBO_BROWSER_SAVE_ROOT` is the only folder the server may write screenshots, PDFs and storage files to, or read storage files from. Leave it out and the current working directory is used.
|
|
46
|
+
|
|
47
|
+
Check the setup, and install Chromium if no browser is found:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
npx -y turbo-browser-mcp --doctor
|
|
51
|
+
npx playwright-core install chromium
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
By default the server first tries a Chrome that is already listening on `http://127.0.0.1:9222`, so the agent can use a browser you are signed in to, and otherwise launches its own headless Chromium. `--mode`, `--headed` and the other options are listed under [CLI options](#cli-options-and-environment-variables).
|
|
55
|
+
|
|
56
|
+
From source:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
git clone https://github.com/Tthanh2k6/turbo-browser-mcp.git
|
|
60
|
+
cd turbo-browser-mcp
|
|
61
|
+
npm install
|
|
62
|
+
node src/index.mjs --doctor
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## Tools
|
|
66
|
+
|
|
67
|
+
| Tool | Purpose | Key Parameters |
|
|
68
|
+
| :--- | :--- | :--- |
|
|
69
|
+
| `tabs_batch` | Ordered tab & browser lifecycle | `operations[]` (`list`, `open`, `open_many`, `navigate`, `activate`, `resize`, `emulate`, `reload`, `back`, `forward`, `close`, `close_browser`), `isolatedContext`, `concurrency` (1-10) |
|
|
70
|
+
| `inspect_compact` | Token-capped element/form/article snapshot | `mode` (`interactive`, `forms`, `article`, `all`), `onlyChanged`, `query`, `boxes`, `maxChars`, `includeFrames`, `savePath` |
|
|
71
|
+
| `smart_fill_form` | Batch form, editor & disk file prefill | `fields[]` (`ref`, `selector`, `value`, `option`, `values`, `check`, `not`, `keys`, `file`, `files`, `frameIdx`, `all`), `gmail`, `overwrite`, `stopBeforeSubmit`, `returnSnapshot` |
|
|
72
|
+
| `act_fast` | Single targeted page action | `action` (`16` actions), `ref`/`selector`/`text`/`label`/`(x, y)`, `modifiers`, `dropData`, `allowSubmit`, `observeAftermath`, `returnSnapshot` |
|
|
73
|
+
| `batch_actions` | Ordered chain of actions + form steps | `steps[]`, `continueOnError`, `allowSubmit`, `expect`, `submissionKey`, `allowDuplicate`, `observeAftermath`, `returnSnapshot`, `snapshotMaxChars` |
|
|
74
|
+
| `extract_clean_text` | Clean text or compact Markdown reader | `format` (`text`, `markdown`), `selector`, `includeFrames`, `maxChars`, `savePath` |
|
|
75
|
+
| `evaluate_js` | Scoped JS expression or `(el, arg)` call | `expression`, `arg`, `frameIdx`, `ref`/`selector`/`text`, `savePath` |
|
|
76
|
+
| `page_diagnostics` | Console, network, downloads & dialogs | `level` (`errors`, `all`), `statusFilter` (`errors`, `all`), `includeStatic`, `urlFilter`, `reqId`, `part`, `dialogPolicy`, `clear`, `savePath` |
|
|
77
|
+
| `capture_page` | PNG/JPEG screenshots & PDF export | `mode` (`screenshot`, `pdf`), `type`, `quality`, `fullPage`, `scale` (`css`, `device`), `ref`/`selector`/`text`, `returnImage`, `savePath` |
|
|
78
|
+
| `network_session` | Resource blockers, cookies & storage | `preset` (`turbo`, `no-images`, `no-media`, `clean`), `blockResources`, `blockUrls`, `cookieAction`, `storageAction`, `loadStorageStatePath`, `saveStorageStatePath` |
|
|
79
|
+
| `wait_for_human` | Hand a step to a person, resume in the same session | `message`, `urlMatches`, `selector`, `textMatches`, `textGone`, `timeoutMs`, `pollMs` |
|
|
80
|
+
|
|
81
|
+
### Examples
|
|
82
|
+
|
|
83
|
+
#### Fill a form, attach a PDF from disk, return the result in the same call
|
|
84
|
+
|
|
85
|
+
```json
|
|
86
|
+
{
|
|
87
|
+
"name": "smart_fill_form",
|
|
88
|
+
"arguments": {
|
|
89
|
+
"fields": [
|
|
90
|
+
{ "selector": "#full_name", "value": "Alex Nguyen" },
|
|
91
|
+
{ "selector": "#email", "value": "alex@example.com" },
|
|
92
|
+
{ "selector": "#country", "option": "United States" },
|
|
93
|
+
{ "selector": "#skills", "values": ["TypeScript", "Playwright"] },
|
|
94
|
+
{ "selector": "#agree_terms", "check": true },
|
|
95
|
+
{ "selector": "#resume_pdf", "file": "./assets/resume.pdf" }
|
|
96
|
+
],
|
|
97
|
+
"stopBeforeSubmit": true,
|
|
98
|
+
"returnSnapshot": true
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
#### Read only what changed after opening a modal
|
|
104
|
+
|
|
105
|
+
```json
|
|
106
|
+
{
|
|
107
|
+
"name": "inspect_compact",
|
|
108
|
+
"arguments": {
|
|
109
|
+
"mode": "interactive",
|
|
110
|
+
"onlyChanged": true,
|
|
111
|
+
"maxChars": 3000
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
#### Open tabs in parallel in separate cookie contexts
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
{
|
|
120
|
+
"name": "tabs_batch",
|
|
121
|
+
"arguments": {
|
|
122
|
+
"operations": [
|
|
123
|
+
{ "action": "open", "url": "https://example.com/app", "isolatedContext": "acct-a" },
|
|
124
|
+
{ "action": "open_many", "urls": ["https://example.com/docs", "https://example.com/pricing"], "concurrency": 4 }
|
|
125
|
+
]
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
#### Allow the final click, check for a receipt, refuse a repeat
|
|
131
|
+
|
|
132
|
+
```json
|
|
133
|
+
{
|
|
134
|
+
"name": "batch_actions",
|
|
135
|
+
"arguments": {
|
|
136
|
+
"steps": [
|
|
137
|
+
{ "action": "smart_fill_form", "fields": [{ "selector": "#name", "value": "홍길동" }] },
|
|
138
|
+
{ "action": "click", "text": "다음" },
|
|
139
|
+
{ "action": "click", "text": "확인" }
|
|
140
|
+
],
|
|
141
|
+
"allowSubmit": true,
|
|
142
|
+
"expect": { "textMatches": "접수번호\\s*R-\\d+", "timeoutMs": 8000 },
|
|
143
|
+
"submissionKey": "photo-contest:2026-11-15:entry-1"
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## What each tool does
|
|
149
|
+
|
|
150
|
+
### Connection and sessions (`tabs_batch`)
|
|
151
|
+
- 4 connection modes (`--mode auto|cdp|persistent|launch`):
|
|
152
|
+
- `auto` (default): probes `--cdp http://127.0.0.1:9222` first so agents can reuse an existing signed-in browser session, then falls back to launching Chromium.
|
|
153
|
+
- `cdp`: attach directly to a running Chromium/Chrome/Edge remote debugging port.
|
|
154
|
+
- `persistent`: launch with a reusable `--user-data-dir` profile across runs.
|
|
155
|
+
- `launch`: start a clean browser session (`--headless` by default, or `--headed`).
|
|
156
|
+
- Auto binary discovery (`src/playwright-loader.mjs`): checks `playwright-core` cache revisions across Windows, macOS, and Linux, system installs of Google Chrome, Microsoft Edge, Brave, and Chromium, or an explicit `--executable <path>`.
|
|
157
|
+
- Per-tab isolation (`tabs_batch`): open tabs inside named `isolatedContext` sandboxes with separate cookies and storage, batch-open up to 10 concurrent URLs (`open_many`), activate, reload, go `back`/`forward`, `resize` viewport, and emulate `colorScheme`, `media`, `reducedMotion`, `contrast`, `forcedColors`, or custom `userAgent`.
|
|
158
|
+
|
|
159
|
+
### Page snapshots (`inspect_compact`)
|
|
160
|
+
- Snapshot modes: `interactive`, `forms`, `article`, and `all`.
|
|
161
|
+
- Cross-boundary traversal: flattens main frame DOM, child iframes (`includeFrames`, `frameIdx`), and open Shadow DOM. Injects an init script hooking `Element.prototype.attachShadow` (`WeakMap` + `WeakRef`/`FinalizationRegistry` + `window.__tbmGetShadowRoot`) to keep post-init closed Shadow roots inspectable and guarded, traverses `<slot>` `assignedNodes({ flatten: true })`, and supports Form-Associated Custom Elements.
|
|
162
|
+
- Token controls: `onlyChanged: true` emits only elements added or changed since the prior snapshot; `query` filters by regex or substring; `boxes: true` adds `[box=x,y,w,h]` only when needed; `maxChars` caps payload size; `savePath` writes full output to disk.
|
|
163
|
+
|
|
164
|
+
### Forms in one call (`smart_fill_form`)
|
|
165
|
+
Prefills an entire form in one MCP call while flushing microtasks and macrotasks between controlled inputs:
|
|
166
|
+
- Standard & framework inputs: text, email, password, number, date, textarea, `<input type="range">`, checkboxes, radio groups (`check`, `not`, `overwrite`). Triggers React-controlled state updates via native property setters and synthetic events.
|
|
167
|
+
- Selects & custom widgets: `<select>` and `<select multiple>` (`option` / `values`), ARIA comboboxes, ARIA switches, `contenteditable` rich editors, and Gmail compose dialogs (`gmail: { to, subject, body }`).
|
|
168
|
+
- Frame & wildcard targeting: target specific iframes via `frameIdx`, or set `all: true` to populate matching controls across frames.
|
|
169
|
+
- Direct disk uploads: pass `file` or `files` paths directly to Playwright `setInputFiles` without loading binary files or Base64 strings into LLM context.
|
|
170
|
+
- Atomic verification: pass `returnSnapshot: true` to inspect the updated form state in the same tool response.
|
|
171
|
+
|
|
172
|
+
### Actions and chains (`act_fast`, `batch_actions`)
|
|
173
|
+
- `act_fast` actions: `click`, `dblclick`, `hover`, `focus`, `clear`, `fill`, `type` (`slowly`, `delayMs`, `submit`), `select`, `check`, `uncheck`, `drag`, `drop` (`file`, `files`, or custom MIME `dropData`), `press` (`key` + `modifiers`: `Alt`, `Control`, `ControlOrMeta`, `Meta`, `Shift`), `scroll` (`dx`, `dy`), `wait` (`ms`, `state`, `loadState`, `text`, `textGone`, `url`), and `upload`.
|
|
174
|
+
- Targeting options: compact `[eN]` `ref`, CSS `selector`, visible `text`, `label`, or viewport `(x, y)` coordinates, with `button` (`left`, `right`, `middle`) and `frameIdx`.
|
|
175
|
+
- `batch_actions`: runs an ordered list of DOM actions and nested `smart_fill_form` steps in one MCP call, stopping safely if blocked by the Submit guard or optionally continuing on step errors (`continueOnError`).
|
|
176
|
+
|
|
177
|
+
### Text, JavaScript and screenshots (`extract_clean_text`, `evaluate_js`, `capture_page`)
|
|
178
|
+
- `extract_clean_text`: extracts readable plain text or compact Markdown (`format: "text" | "markdown"`) from main/article containers and iframes, stripped of script and style noise.
|
|
179
|
+
- `evaluate_js`: runs JS expressions or `(el, arg)` element functions in any frame (`frameIdx`) with JSON-serialized results and optional `savePath` export.
|
|
180
|
+
- `capture_page`: full-page or element-scoped screenshots (`png` or `jpeg` with `quality`, `css` or `device` scale, optional `returnImage`) and PDF generation saved to a confined `savePath`.
|
|
181
|
+
|
|
182
|
+
### Network, storage and diagnostics (`network_session`, `page_diagnostics`)
|
|
183
|
+
- `network_session` presets: `turbo`, `no-images`, `no-media`, and `clean` (unblock all), alongside custom `blockResources` and `blockUrls` patterns.
|
|
184
|
+
- Session & storage management: read/write/clear browser `cookies`, `localStorage`/`sessionStorage`, and export or reload full Playwright `storageState` JSON files (`saveStorageStatePath`, `loadStorageStatePath`).
|
|
185
|
+
- `page_diagnostics`: defaults to errors-only (`level: "errors"`, `statusFilter: "errors"`) to surface failures cleanly without flooding context, while supporting `all`, `includeStatic`, `urlFilter`, deep request/response inspection (`reqId` + `part`), completed downloads, and dialog auto-handling (`dialogPolicy`: `accept`/`dismiss`).
|
|
186
|
+
|
|
187
|
+
## Benchmarks
|
|
188
|
+
|
|
189
|
+
### Per-tool measurements (`npm run benchmark`)
|
|
190
|
+
|
|
191
|
+
These come from [`benchmarks/benchmark.mjs`](benchmarks/benchmark.mjs) on local fixture pages in headless Chromium. Tokens are counted with `tiktoken` (`o200k_base`). They measure the size of tool output and the time spent in the browser. Model time is not included, so read them as an upper bound on what an agent gains, not as an agent result.
|
|
192
|
+
|
|
193
|
+
"Cumulative" tokens model a chat agent that re-reads every earlier tool result on each turn: over N turns, the output of turn i is read N − i + 1 times. Each call saved is also one model round-trip, which in most agent loops takes longer than the browser work itself.
|
|
194
|
+
|
|
195
|
+
### Snapshots and text extraction
|
|
196
|
+
|
|
197
|
+
| Scenario | Raw HTML | Full Playwright ARIA | `turbo-browser-mcp` Output | Saved vs ARIA | Saved vs HTML |
|
|
198
|
+
| :--- | :--- | :--- | :--- | :--- | :--- |
|
|
199
|
+
| 140-Button SaaS Console (`inspect_compact`) | `61,010` chars (`18,654` tok) | `12,771` chars (`3,568` tok) | `3,968` chars (`1,135` tok) | `68.2%` | `93.9%` |
|
|
200
|
+
| Post-Click Delta (`onlyChanged: true`) | `61,010` chars (`18,654` tok) | `12,825` chars (`3,582` tok) | `168` chars (`56` tok) | `98.4%` | `99.7%` |
|
|
201
|
+
| Article Markdown Extraction (`extract_clean_text`) | `10,844` chars (`3,595` tok) | n/a | `641` chars (`156` tok) | n/a | `95.7%` |
|
|
202
|
+
| Diagnostics Filter (`32` reqs, `26` console logs) | `9,651` chars (`3,460` tok, `all`) | n/a | `1,761` chars (`601` tok, `errors`) | n/a | `82.6%` |
|
|
203
|
+
|
|
204
|
+
### Forms, multi-step flows, uploads and page loading
|
|
205
|
+
|
|
206
|
+
| Scenario | Step-by-Step Baseline | `turbo-browser-mcp` | Execution Speedup | Token Savings |
|
|
207
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
208
|
+
| 10-Field Complex Form + Verify (`smart_fill_form`) | `11` turns, `574 ms`, `12,197` direct / `72,614` cum tok | `1` turn, `82 ms`, `811` tok (`filled=10`) | `7x` faster | `93.4%` dir / `98.9%` cum |
|
|
209
|
+
| 48 KiB PDF Upload (`49,152` bytes via `file`) | `65,679` chars (`44,728` tok) Base64 payload | `263` chars (`85` tok) disk path (`68 ms`) | Zero LLM Base64 encode | `99.8%` |
|
|
210
|
+
| 6-Step UI Flow (`batch_actions`) | `6` turns, `411 ms`, `955` dir / `3,162` cum tok | `1` turn, `357 ms`, `406` tok | `1.15x` faster | `57.5%` dir / `87.2%` cum |
|
|
211
|
+
| Open 6 Tabs (`tabs_batch` `open_many`, `60 ms` TTFB) | `6` turns sequential (`998 ms`) | `1` turn batched (`420 ms`) | `2.38x` faster (`6 -> 1` turns) | Eliminates `5` turns |
|
|
212
|
+
| Heavy Media Load (`8x32 KiB` imgs + `48 KiB` font) | `252 ms`, `9` media hits (`304 KiB`) | `165 ms`, `0` media hits (`0 KiB`) | `1.53x` faster | `100%` media saved |
|
|
213
|
+
|
|
214
|
+
### Tool schema size (sent to the model on every turn)
|
|
215
|
+
|
|
216
|
+
Measured against installed MCP JSON schemas on disk (compact parameter schemas without `annotations`):
|
|
217
|
+
|
|
218
|
+
| MCP Server | Tool Count | Compact Schema Chars | Exact `o200k_base` Tokens | Savings with `turbo-browser-mcp` |
|
|
219
|
+
| :--- | :--- | :--- | :--- | :--- |
|
|
220
|
+
| `turbo-browser-mcp` | `11` (`15,144` full / `13,631` compact) | `13,631` | `3,170` (`3,541` full w/ annotations) | Baseline (`11` tools) |
|
|
221
|
+
| `@playwright/mcp` | `25` | `18,457` | `3,917` | `19.1%` fewer static tokens |
|
|
222
|
+
| `chrome-devtools-mcp` | `33` | `30,252` | `6,737` | `52.9%` fewer static tokens |
|
|
223
|
+
|
|
224
|
+
v0.5.0 added `wait_for_human` and the commit-safety parameters for about 160 tokens per turn (v0.4.0: `3,010` compact). To keep that small, `expect` / `submissionKey` / `allowDuplicate` are declared only on `batch_actions` (a one-step batch works for a single click), and the network guard is switched on by environment variable, so it costs no schema tokens. The label lists for other languages run inside the page and are never sent to the model.
|
|
225
|
+
|
|
226
|
+
### Scripted end-to-end task (`npm run benchmark:e2e`)
|
|
227
|
+
|
|
228
|
+
[`benchmarks/E2E_COMPARISON.md`](benchmarks/E2E_COMPARISON.md) runs a fixed script against a Korean-language contest wizard (6 fields, a `다음` step, a `확인` inside a modal, a receipt page). One action per call with a full ARIA snapshot after each takes 9 calls and 32,942 cumulative context tokens. `inspect_compact` plus one `batch_actions` call with `expect` takes 2 calls and 1,430 tokens, and confirms the receipt number itself. The same file covers the commit-safety cases.
|
|
229
|
+
|
|
230
|
+
### Agent benchmark against other browser stacks (in progress)
|
|
231
|
+
|
|
232
|
+
[`benchmarks/e2e-agent/`](benchmarks/e2e-agent/) gives a coding agent three tasks on local fixture sites (a job application with a file upload, a catalog search, a booking with a confirmation step) and runs it with each stack: turbo-browser-mcp, agent-browser, browse and browser-use. A separate script checks each result on the server side, and the runner records model tokens and wall time. The plan and success checks are in [`benchmarks/E2E_PLAN.md`](benchmarks/E2E_PLAN.md). Results will be added here once every stack has finished all three tasks. Until then, the numbers above say nothing about how this server compares with those tools in a full agent run.
|
|
233
|
+
|
|
234
|
+
## Comparison with `@playwright/mcp` and `chrome-devtools-mcp`
|
|
235
|
+
|
|
236
|
+
| Feature | `turbo-browser-mcp` | `@playwright/mcp` | `chrome-devtools-mcp` |
|
|
237
|
+
| :--- | :--- | :--- | :--- |
|
|
238
|
+
| Number of tools | 11 | 25 granular tools | 33 granular tools |
|
|
239
|
+
| Delta Snapshots (`onlyChanged`) | Built-in | Full tree every snapshot | Full tree every snapshot |
|
|
240
|
+
| Closed Shadow DOM Hook | Post-init `attachShadow` hook + `<slot>` flattening | Open Shadow DOM | CDP / standard DOM access |
|
|
241
|
+
| Single-Call Smart Form + Contenteditable | Yes (React, Shadow DOM, iframe, Gmail, ranges) | Multi-turn fill + separate select calls | Basic `fill_form` |
|
|
242
|
+
| Disk File Upload (Zero Base64) | Native `file`/`files` path in `smart_fill_form` & `act_fast` | Dedicated `browser_file_upload` turn | Dedicated `upload_file` turn |
|
|
243
|
+
| Default Human-in-the-Loop Submit Guard | Yes (`allowSubmit=false`, form/iframe/Enter hooks) | No | No |
|
|
244
|
+
| Parallel `open_many` + `isolatedContext` | Single batched call | Separate sequential tab calls | Separate page calls |
|
|
245
|
+
| One-Call `turbo` Media Blocker | Built-in (`turbo`, `no-images`, `no-media`) | Manual JS / routing | Network emulation |
|
|
246
|
+
| Performance / Heap Profiling | Not included | Not included | Trace, Lighthouse, Heap Snapshot |
|
|
247
|
+
|
|
248
|
+
> When to keep Chrome DevTools MCP alongside `turbo-browser-mcp`: `chrome-devtools-mcp` provides Lighthouse audits, performance trace analysis, CSS computed style panels, and V8 heap snapshots. `turbo-browser-mcp` focuses on fast multi-step UI automation, forms, and scraping with minimal token overhead.
|
|
249
|
+
|
|
250
|
+
### Tool mapping
|
|
251
|
+
|
|
252
|
+
| Capability | `turbo-browser-mcp` | `@playwright/mcp` | `chrome-devtools-mcp` |
|
|
253
|
+
| :--- | :--- | :--- | :--- |
|
|
254
|
+
| Multi-tab open, list, switch, resize, emulate | `tabs_batch` | `browser_tabs`, `browser_navigate`, `browser_resize`, ... | `new_page`, `list_pages`, `select_page`, `resize_page`, ... |
|
|
255
|
+
| DOM / accessibility inspection | `inspect_compact` | `browser_snapshot` | `take_snapshot` |
|
|
256
|
+
| Multi-field form & upload | `smart_fill_form` | `browser_fill_form` + `browser_select_option` + `browser_file_upload` | `fill_form` + `upload_file` |
|
|
257
|
+
| Click, type, drag, press, scroll, wait | `act_fast` | `browser_click`, `browser_type`, `browser_drag`, ... | `click`, `type_text`, `drag`, `press_key`, `wait_for` |
|
|
258
|
+
| Multi-step sequential macro | `batch_actions` | `browser_run_code_unsafe` or N tool calls | N separate tool calls |
|
|
259
|
+
| Clean article extraction | `extract_clean_text` | `browser_evaluate` custom JS | `evaluate_script` custom JS |
|
|
260
|
+
| Frame/element JS evaluation | `evaluate_js` | `browser_evaluate` | `evaluate_script` |
|
|
261
|
+
| Errors, network & console triage | `page_diagnostics` | `browser_console_messages`, `browser_network_requests` | `list_console_messages`, `list_network_requests`, ... |
|
|
262
|
+
| Screenshots & PDF export | `capture_page` | `browser_take_screenshot` | `take_screenshot` |
|
|
263
|
+
| Blocking presets, cookies & storage | `network_session` | `browser_evaluate` + context config | Partial via `evaluate_script` / `emulate` |
|
|
264
|
+
|
|
265
|
+
## Safety
|
|
266
|
+
|
|
267
|
+
### Submit guard and file path limits
|
|
268
|
+
|
|
269
|
+
1. Human-in-the-loop Submit Guard (`allowSubmit=false` by default):
|
|
270
|
+
- `smart_fill_form` (`stopBeforeSubmit: true`), `act_fast`, and `batch_actions` inspect matching elements, W3C AccName labels (`isSafeSubmitter`), implicit HTML form Enter submissions, key chords (`Shift+Enter`, `Enter+Shift`), `HTMLFormElement.prototype.submit`/`requestSubmit`, and same-origin iframe `contentWindow`/`contentDocument` proxies.
|
|
271
|
+
- Final actions resembling `Submit`, `Publish`, `Send`, `Post`, `Apply`, `Confirm`, or payment triggers are blocked unless `allowSubmit: true` is explicitly passed or `--allow-submit` is enabled at startup.
|
|
272
|
+
- Trade-off: pre-existing closed Shadow roots on already-open CDP tabs (attached before the init script ran) or strict cross-origin sandboxed frames fall back to Playwright frame handles, coordinate actions, and keyboard input.
|
|
273
|
+
2. Workspace Path Confinement (`TURBO_BROWSER_SAVE_ROOT`):
|
|
274
|
+
- File outputs (`savePath`, `saveStorageStatePath`) and state inputs (`loadStorageStatePath`) are strictly confined to the current working directory or `TURBO_BROWSER_SAVE_ROOT`.
|
|
275
|
+
- Lexical checks, `lstatSync`/`readlinkSync` symlink verification, and `realpathSync` validation block `..` traversal, UNC network paths, dangling symlinks, cyclic symlinks, and Windows junctions before reading or writing.
|
|
276
|
+
|
|
277
|
+
### Commit checks: `expect`, `submissionKey`, modal and network guards
|
|
278
|
+
|
|
279
|
+
Readers who run agents on real portals pointed out three gaps in a label-based guard. v0.5.0 adds an opt-in answer to each. `expect`, `submissionKey` and `allowDuplicate` appear in the `batch_actions` schema; `act_fast` accepts the same arguments without advertising them. The network guard is turned on with `TURBO_BROWSER_NETWORK_GUARD=true` and covers `act_fast`, `batch_actions` and `smart_fill_form`.
|
|
280
|
+
|
|
281
|
+
1. A landed click is not a confirmed submission → `expect`. After an allowed submit, pass `expect: { urlMatches?, textMatches?, selector?, timeoutMs? }`. The result carries `submitVerified` and `evidence` (the new URL, a text snippet such as a receipt number, or the matched selector). If nothing shows up in time you get `submitVerified: false` and a reason, so the agent does not report "done" on an empty submission list.
|
|
282
|
+
2. A re-run is a second entry, not a retry → `submissionKey`. With `submissionKey: "portal:2026-11-15:entry-42"`, every allowed submit is appended to a JSONL ledger (`~/.turbo-browser-mcp/submissions.jsonl`, or `TURBO_BROWSER_LEDGER`, or `ledgerPath` inside the save root). A later call with the same key is refused with `blockedBy: "ledger"` unless `allowDuplicate: true`.
|
|
283
|
+
3. Labels lie → modal rule + `networkGuard`. On many Korean portals the last step reads 다음 and the real commit is a 확인 inside a modal that opens afterwards.
|
|
284
|
+
- Affirmative buttons (`확인`, `OK`, `Yes`, `Confirm`, `確認`, `确定`, `Đồng ý`, …) inside `dialog` / `[role=dialog]` / `[role=alertdialog]` / `[aria-modal=true]` now count as commits (`blockedBy: "modal"`). Cookie banners (dialog text mentions cookies) and date/time pickers (dialog contains a calendar grid or date input) are excluded; a confirmation that only mentions "privacy" or "consent" is still blocked.
|
|
285
|
+
- When an action makes the page call `form.submit()` / `requestSubmit()` or fire a `submit` event and the guard stops it, the result now says so (`submitSuppressed`, `note`) instead of a bare `ok: true`. The action itself (a select, a check) still counts as done, so batches continue.
|
|
286
|
+
- Common Korean, Japanese, Chinese and Vietnamese submit labels were added (`제출`, `신청`, `등록`, `결제`, `送信`, `確定`, `提交`, `Hoàn tất`, …), and `다음`, `次へ`, `下一步` are treated like `Next`.
|
|
287
|
+
- `TURBO_BROWSER_NETWORK_GUARD=true` is the safety net that does not depend on labels: while submitting is not allowed, non-GET navigations and same-site `fetch`/XHR `POST`/`PUT`/`PATCH`/`DELETE` are stopped and reported (`blockedBy: "network"`, `networkBlocked[]`). Blocked navigations get a `204` so the page and the half-filled form stay put. Let harmless endpoints through with `TURBO_BROWSER_NETWORK_GUARD_ALLOW="/autosave$,/analytics"`. Per call, the undeclared arguments `networkGuard`, `networkGuardAllow` and `networkGuardSettleMs` override the env values. It is off by default because multi-step wizards often `POST` on every "Next".
|
|
288
|
+
- Every blocked result now says which mechanism stopped it: `blockedBy` is `label`, `modal`, `network` or `ledger`.
|
|
289
|
+
|
|
290
|
+
Limits:
|
|
291
|
+
- The network guard watches the action plus `networkGuardSettleMs` (250 ms) afterwards, so a commit fired later by a timer is not caught. WebSocket messages, requests made by a service worker, and cross-site `fetch` POSTs are not inspected (cross-site *navigations* are). Patterns in `TURBO_BROWSER_NETWORK_GUARD_ALLOW` are split on commas, so a pattern cannot contain one.
|
|
292
|
+
- The ledger is written only when the call returns. If the call throws after the page already sent the submission (for example a navigation timeout), nothing is recorded; check the site before re-running.
|
|
293
|
+
- `expect.selector` that is not a valid selector never matches, so the call reports `submitVerified: false` after the timeout.
|
|
294
|
+
|
|
295
|
+
### Handing a step to a person (`wait_for_human`, `--open-profile`)
|
|
296
|
+
|
|
297
|
+
Some sites fail their bot check whenever the browser is remote-controlled, so a person has to open the same profile in a normal browser first. turbo-browser-mcp does not try to hide automation: no stealth plugins, no fingerprint or `navigator.webdriver` patching, no CAPTCHA solving. It supports two hand-off flows instead.
|
|
298
|
+
|
|
299
|
+
1. Before the session: `turbo-browser-mcp --open-profile --url https://site.example/login` opens plain Chrome (no debugging port, no automation flags) on the dedicated profile `~/.turbo-browser-mcp/chrome-profile` (or `--user-data-dir`). The human logs in or passes the check and closes the window. Then start the server with `--user-data-dir <same path>` or `--launch-chrome`, and the agent reuses those cookies. This works for sites that check at login; a site that re-checks on every request will still see an automated browser.
|
|
300
|
+
2. During the session: the agent calls `wait_for_human` with a message and a condition (`urlMatches`, `selector`, `textMatches` or `textGone`). The tool brings the tab to the front and polls until the condition holds, then the agent continues in the same tab with the same cookies. Keep `timeoutMs` below your MCP client's request timeout and call it again to keep waiting.
|
|
301
|
+
|
|
302
|
+
```json
|
|
303
|
+
{
|
|
304
|
+
"name": "wait_for_human",
|
|
305
|
+
"arguments": {
|
|
306
|
+
"message": "Please sign in and finish the security check, then leave the tab open.",
|
|
307
|
+
"selector": "#account-menu",
|
|
308
|
+
"timeoutMs": 120000
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
## Click aftermath reporting
|
|
314
|
+
|
|
315
|
+
Set `observeAftermath: true` on `act_fast` or `batch_actions` (or set
|
|
316
|
+
`TURBO_BROWSER_OBSERVE_AFTERMATH=true`) to observe navigation and mutating
|
|
317
|
+
fetch/XHR requests for one second after each click. It is off by default.
|
|
318
|
+
The result includes `aftermath: { beforeUrl, afterUrl, navigated,
|
|
319
|
+
mutatingRequests, unexpectedSubmit }`. Requests include their method, URL,
|
|
320
|
+
and a `finalSubmit` classification. Main-frame origin/path changes or
|
|
321
|
+
commit-like requests produce a warning when `allowSubmit` is false.
|
|
322
|
+
|
|
323
|
+
This reports an action that has already occurred. It cannot prevent a commit
|
|
324
|
+
or prove that a submission succeeded. Wizard navigation can trigger a warning,
|
|
325
|
+
and opaque endpoints or requests outside the observation window can be missed.
|
|
326
|
+
Use the network guard for prevention and `expect` for receipt verification.
|
|
327
|
+
See [fixture and classification details](test/COMMUNITY_FIXTURES.md).
|
|
328
|
+
|
|
329
|
+
## CLI options and environment variables
|
|
330
|
+
|
|
331
|
+
| CLI Flag | Environment Variable | Default | Description |
|
|
332
|
+
| :--- | :--- | :--- | :--- |
|
|
333
|
+
| `--mode <auto\|cdp\|persistent\|launch>` | `TURBO_BROWSER_MODE` | `auto` | Connection strategy (`cdp` first then launch in `auto`) |
|
|
334
|
+
| `--cdp <url>` | `TURBO_BROWSER_CDP_URL` | `http://127.0.0.1:9222` | Chrome DevTools Protocol HTTP endpoint |
|
|
335
|
+
| `--user-data-dir <path>` | `TURBO_BROWSER_USER_DATA_DIR` | `""` | Persistent profile directory path |
|
|
336
|
+
| `--executable <path>` | - | auto-detected | Custom Chromium, Chrome, Edge, or Brave executable |
|
|
337
|
+
| `--timeout <ms>` | `TURBO_BROWSER_TIMEOUT_MS` | `15000` | Default Playwright action/navigation timeout in ms |
|
|
338
|
+
| `--headless` / `--headed` | `TURBO_BROWSER_HEADLESS` | `true` (headless) | Run headless or visible browser window (`"false"` for headed) |
|
|
339
|
+
| `--allow-submit` | - | `false` | Disable default Submit/Publish confirmation guard |
|
|
340
|
+
| `--doctor` | - | - | Print Node, Playwright, Chromium, and CDP diagnostics as JSON |
|
|
341
|
+
| `--bridge` | `TURBO_BROWSER_BRIDGE_PORT` | `9224` | Start/verify the persistent CDP Keep-Alive Bridge daemon for Chrome 144+ `DevToolsActivePort` (approve once, reconnect unlimited times AFK) |
|
|
342
|
+
| `--launch-chrome` | - | `~/.turbo-browser-mcp/chrome-profile` | Launch Chrome with a dedicated profile & `--remote-debugging-port=9222` (`0` approval prompts ever) |
|
|
343
|
+
| `--open-profile [--url <u>]` | `TURBO_BROWSER_OPEN_URL` | `~/.turbo-browser-mcp/chrome-profile` | Open the profile in a normal, non-automated Chrome so a human can log in or pass a check first |
|
|
344
|
+
| - | `TURBO_BROWSER_NETWORK_GUARD` | `false` | Turn on the network commit guard by default |
|
|
345
|
+
| - | `TURBO_BROWSER_NETWORK_GUARD_ALLOW` | `""` | Comma-separated URL regexes the network guard lets through |
|
|
346
|
+
| - | `TURBO_BROWSER_OBSERVE_AFTERMATH` | `false` | Report navigation and mutating requests after each click (see [Click aftermath](#click-aftermath-reporting)) |
|
|
347
|
+
| - | `TURBO_BROWSER_LEDGER` | `~/.turbo-browser-mcp/submissions.jsonl` | Submission ledger used by `submissionKey` |
|
|
348
|
+
| `--version` / `-v` | - | - | Print server version |
|
|
349
|
+
| `--help` / `-h` | - | - | Print CLI usage summary |
|
|
350
|
+
| - | `TURBO_BROWSER_SAVE_ROOT` | `process.cwd()` | Root directory confining `savePath` and `storageState` files |
|
|
351
|
+
| - | `PLAYWRIGHT_CORE_PATH` | auto-resolved | Explicit path to `playwright-core/index.mjs` |
|
|
352
|
+
|
|
353
|
+
### Unattended runs and the Chrome 144+ remote-debugging prompt
|
|
354
|
+
|
|
355
|
+
In Chrome 136+/144+, enabling `chrome://inspect/#remote-debugging` on the default `User Data` directory exposes a WebSocket in `DevToolsActivePort` that displays an "Allow remote debugging?" prompt whenever a new WebSocket client connects. `turbo-browser-mcp` provides two built-in solutions so overnight AFK multi-agent runs never hang on a prompt:
|
|
356
|
+
|
|
357
|
+
1. Automatic CDP Keep-Alive Bridge Daemon (`npm run bridge` / `--bridge`, enabled automatically on `DevToolsActivePort`):
|
|
358
|
+
- Spawns a detached background multiplexer (`src/cdp-bridge.mjs` on `http://127.0.0.1:9224`) that holds one persistent upstream WebSocket to Chrome open indefinitely and intercepts `Browser.close` so downstream scripts never terminate your browser.
|
|
359
|
+
- You click Allow once when starting your session; afterwards, any number of MCP servers, CLI scripts, or subagents can connect and disconnect all night with 0 additional prompts.
|
|
360
|
+
2. Zero-Prompt Dedicated Profile Launcher (`npm run launch-chrome` / `--launch-chrome`):
|
|
361
|
+
- Launches Chrome with `--remote-debugging-port=9222` and a dedicated `--user-data-dir` (`~/.turbo-browser-mcp/chrome-profile`), where Chrome exposes standard HTTP/WS CDP with 0 confirmation dialogs even on the very first connection.
|
|
362
|
+
|
|
363
|
+
## Development
|
|
364
|
+
|
|
365
|
+
```bash
|
|
366
|
+
npm test # 437 tests in 87 suites (test/*.test.mjs)
|
|
367
|
+
npm run doctor # Node, Playwright, Chromium and CDP check
|
|
368
|
+
npm run benchmark # per-tool token and timing benchmark
|
|
369
|
+
npm run benchmark:e2e # scripted wizard task and commit-safety cases
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
CI runs the tests on Ubuntu with Node 20 and 22.
|
|
373
|
+
|
|
374
|
+
## Known limits
|
|
375
|
+
|
|
376
|
+
- Portaled comboboxes (react-select, Radix, Headless UI style) have a click path and a keyboard fallback that searches up to 100 options and checks the committed value. Virtualized lists beyond the included fixtures still need testing against real apps.
|
|
377
|
+
- Sites with bot detection may need `wait_for_human` and a person to pass the check in the same browser. The server does not bypass those checks.
|
|
378
|
+
- The network guard and click aftermath only watch a short window after each action, and do not inspect WebSocket messages or service-worker requests. Details are under [commit checks](#commit-checks-expect-submissionkey-modal-and-network-guards).
|
|
379
|
+
- Closed Shadow roots that existed before the server attached to a tab cannot be reached through the hook. Actions there fall back to frame handles, coordinates and keyboard input.
|
|
380
|
+
|
|
381
|
+
## Credits
|
|
382
|
+
|
|
383
|
+
Several features came from readers of the Show HN post and the dev.to article: johnnylemonny and alexcodebytes (portaled and virtualized selects), eye_java_420f1faa10ae8b86 (keyboard selection and click aftermath), amintacccp (safe submit labels), snake_doc and lukevp (end-to-end comparison, level of abstraction), vidarh (human hand-off), harrysong138759 (receipt verification and duplicate submissions).
|
|
384
|
+
|
|
385
|
+
## License
|
|
386
|
+
|
|
387
|
+
[MIT](LICENSE)
|
package/package.json
CHANGED
|
@@ -1,6 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "turbo-browser-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.6.1",
|
|
4
|
+
"description": "Fast, token-efficient MCP server for Playwright browser automation with batched DOM actions, React/Shadow DOM/contenteditable form prefill, isolated contexts, download/network diagnostics, and direct disk file uploads.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./src/index.mjs",
|
|
7
|
+
"bin": {
|
|
8
|
+
"turbo-browser-mcp": "src/index.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"src/",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE",
|
|
14
|
+
"server.json"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"start": "node ./src/index.mjs",
|
|
18
|
+
"test": "node --test --test-concurrency=4 test/*.test.mjs",
|
|
19
|
+
"doctor": "node ./src/index.mjs --doctor",
|
|
20
|
+
"bridge": "node ./src/index.mjs --bridge",
|
|
21
|
+
"launch-chrome": "node ./src/index.mjs --launch-chrome",
|
|
22
|
+
"benchmark": "node ./benchmarks/benchmark.mjs",
|
|
23
|
+
"benchmark:e2e": "node ./benchmarks/e2e-tasks.mjs"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"mcp",
|
|
27
|
+
"model-context-protocol",
|
|
28
|
+
"playwright",
|
|
29
|
+
"browser-automation",
|
|
30
|
+
"cdp",
|
|
31
|
+
"shadow-dom",
|
|
32
|
+
"llm-agent"
|
|
33
|
+
],
|
|
34
|
+
"author": "Trung Thanh Tran",
|
|
35
|
+
"license": "MIT",
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=20.0.0"
|
|
38
|
+
},
|
|
39
|
+
"dependencies": {
|
|
40
|
+
"playwright-core": ">=1.49.0"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/server.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-10-17/server.schema.json",
|
|
3
|
+
"name": "io.github.tthanh2k6/turbo-browser-mcp",
|
|
4
|
+
"description": "Fast, token-efficient Playwright MCP server with batched form fill, Shadow DOM inspection, isolated sessions, download capture, and human-in-the-loop submit guard.",
|
|
5
|
+
"version": "0.6.1",
|
|
6
|
+
"repository": {
|
|
7
|
+
"url": "https://github.com/Tthanh2k6/turbo-browser-mcp",
|
|
8
|
+
"source": "github"
|
|
9
|
+
},
|
|
10
|
+
"packages": [
|
|
11
|
+
{
|
|
12
|
+
"registryType": "npm",
|
|
13
|
+
"identifier": "turbo-browser-mcp",
|
|
14
|
+
"version": "0.6.1",
|
|
15
|
+
"transport": {
|
|
16
|
+
"type": "stdio"
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
]
|
|
20
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// Observation only: this cannot undo a request or establish submission success.
|
|
2
|
+
export function observeClickAftermath(page) {
|
|
3
|
+
const beforeUrl = page.url();
|
|
4
|
+
const mutatingRequests = [];
|
|
5
|
+
let navigated = false;
|
|
6
|
+
const pathChanged = (url) => {
|
|
7
|
+
try {
|
|
8
|
+
const before = new URL(beforeUrl), after = new URL(url);
|
|
9
|
+
return before.origin !== after.origin || before.pathname !== after.pathname;
|
|
10
|
+
} catch { return url !== beforeUrl; }
|
|
11
|
+
};
|
|
12
|
+
const onNavigation = (frame) => {
|
|
13
|
+
if (frame === page.mainFrame() && pathChanged(frame.url())) navigated = true;
|
|
14
|
+
};
|
|
15
|
+
const onRequest = (request) => {
|
|
16
|
+
const method = request.method();
|
|
17
|
+
if (!/^(POST|PUT|PATCH|DELETE)$/.test(method) || !['fetch', 'xhr'].includes(request.resourceType())) return;
|
|
18
|
+
const url = request.url();
|
|
19
|
+
let pathname = '';
|
|
20
|
+
try { pathname = new URL(url).pathname; } catch {}
|
|
21
|
+
const finalSubmit = method === 'DELETE' ||
|
|
22
|
+
/(?:^|[/_.-])(?:submit|publish|commit|checkout|payment|purchase|delete)(?:$|[/_.-])/i.test(pathname);
|
|
23
|
+
mutatingRequests.push({ method, url, finalSubmit });
|
|
24
|
+
};
|
|
25
|
+
page.on('request', onRequest);
|
|
26
|
+
page.on('framenavigated', onNavigation);
|
|
27
|
+
return {
|
|
28
|
+
async finish(result, allowSubmit) {
|
|
29
|
+
if (!result || result.blocked) return;
|
|
30
|
+
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
31
|
+
const unexpectedSubmit = !allowSubmit && (navigated || mutatingRequests.some((r) => r.finalSubmit));
|
|
32
|
+
result.aftermath = { beforeUrl, afterUrl: page.url(), navigated, mutatingRequests, unexpectedSubmit };
|
|
33
|
+
if (unexpectedSubmit) {
|
|
34
|
+
result.aftermath.warning = 'Possible final submit observed despite allowSubmit=false. The action already occurred; inspect the result before retrying.';
|
|
35
|
+
}
|
|
36
|
+
},
|
|
37
|
+
remove() {
|
|
38
|
+
page.off('request', onRequest);
|
|
39
|
+
page.off('framenavigated', onNavigation);
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
}
|