Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

P5b: readability /text, split handler_snapshot.go, remove deprecated stealth flag

bot7425481f234a
diff --git a/TODO.md b/TODO.md
index 294ba9e8..ef889973 100644
--- a/TODO.md
+++ b/TODO.md
@@ -72,13 +72,13 @@ Split into 8 files (single package):
- [x] **21 tests passing** — diff, text format, all existing tests green
## P5 Remaining
-
-## P5 Bugs & Stealth
-- [ ] **Remove `--disable-blink-features=AutomationControlled` flag** — deprecated in Chrome 144+, triggers warning banner in headed mode, hurts stealth. JS injection already patches `navigator.webdriver`
-- [ ] **Better /text** — Readability-style extraction instead of raw innerText
-- [ ] **Split handlers.go** — snapshot handler is complex enough for its own file
- [ ] **Wire interfaces into handlers** — Inject Browser/TabManager so handler tests don't need Chrome
+## Done ✅ (P5b)
+- [x] **Remove `--disable-blink-features=AutomationControlled` flag** — deprecated in Chrome 144+, stealth.js handles it
+- [x] **Better /text** — Readability-style extraction (`readability.js`), strips nav/footer/aside/ads, prefers article/main. `?mode=raw` for old innerText.
+- [x] **Split handlers.go** — snapshot handler extracted to `handler_snapshot.go`
+
## P7: Nice to Have
- [ ] **File-based output** — `?output=file` saves snapshot to disk, returns path (Playwright CLI approach)
- [ ] **Compact format** — YAML or indented text instead of JSON
diff --git a/config.go b/config.go
index 9036e2d9..28f005a1 100644
--- a/config.go
+++ b/config.go
@@ -37,6 +37,9 @@ const (
//go:embed stealth.js
var stealthScript string
+//go:embed readability.js
+var readabilityJS string
+
var (
port = envOr("BRIDGE_PORT", "9867")
cdpURL = os.Getenv("CDP_URL") // empty = launch Chrome ourselves
diff --git a/handler_snapshot.go b/handler_snapshot.go
new file mode 100644
index 00000000..5820e07b
--- /dev/null
+++ b/handler_snapshot.go
@@ -0,0 +1,113 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "strconv"
+
+ "github.com/chromedp/chromedp"
+)
+
+// ── GET /snapshot ──────────────────────────────────────────
+
+func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
+ tabID := r.URL.Query().Get("tabId")
+ filter := r.URL.Query().Get("filter")
+ doDiff := r.URL.Query().Get("diff") == "true"
+ format := r.URL.Query().Get("format") // "text" for indented tree
+ maxDepthStr := r.URL.Query().Get("depth")
+ maxDepth := -1
+ if maxDepthStr != "" {
+ if d, err := strconv.Atoi(maxDepthStr); err == nil {
+ maxDepth = d
+ }
+ }
+
+ ctx, resolvedTabID, err := b.TabContext(tabID)
+ if err != nil {
+ jsonErr(w, 404, err)
+ return
+ }
+
+ tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
+ defer tCancel()
+ go cancelOnClientDone(r.Context(), tCancel)
+
+ var rawResult json.RawMessage
+ if err := chromedp.Run(tCtx,
+ chromedp.ActionFunc(func(ctx context.Context) error {
+ return chromedp.FromContext(ctx).Target.Execute(ctx,
+ "Accessibility.getFullAXTree", nil, &rawResult)
+ }),
+ ); err != nil {
+ jsonErr(w, 500, fmt.Errorf("a11y tree: %w", err))
+ return
+ }
+
+ var treeResp struct {
+ Nodes []rawAXNode `json:"nodes"`
+ }
+ if err := json.Unmarshal(rawResult, &treeResp); err != nil {
+ jsonErr(w, 500, fmt.Errorf("parse a11y tree: %w", err))
+ return
+ }
+
+ flat, refs := buildSnapshot(treeResp.Nodes, filter, maxDepth)
+
+ // Get previous snapshot for diff before overwriting cache
+ var prevNodes []A11yNode
+ if doDiff {
+ b.mu.RLock()
+ if prev := b.snapshots[resolvedTabID]; prev != nil {
+ prevNodes = prev.nodes
+ }
+ b.mu.RUnlock()
+ }
+
+ // Cache ref→nodeID mapping and nodes for this tab
+ b.mu.Lock()
+ b.snapshots[resolvedTabID] = &refCache{refs: refs, nodes: flat}
+ b.mu.Unlock()
+
+ var url, title string
+ _ = chromedp.Run(tCtx,
+ chromedp.Location(&url),
+ chromedp.Title(&title),
+ )
+
+ if doDiff && prevNodes != nil {
+ added, changed, removed := diffSnapshot(prevNodes, flat)
+ jsonResp(w, 200, map[string]any{
+ "url": url,
+ "title": title,
+ "diff": true,
+ "added": added,
+ "changed": changed,
+ "removed": removed,
+ "counts": map[string]int{
+ "added": len(added),
+ "changed": len(changed),
+ "removed": len(removed),
+ "total": len(flat),
+ },
+ })
+ return
+ }
+
+ if format == "text" {
+ w.Header().Set("Content-Type", "text/plain; charset=utf-8")
+ w.WriteHeader(200)
+ fmt.Fprintf(w, "# %s\n# %s\n# %d nodes\n\n", title, url, len(flat))
+ w.Write([]byte(formatSnapshotText(flat)))
+ return
+ }
+
+ jsonResp(w, 200, map[string]any{
+ "url": url,
+ "title": title,
+ "nodes": flat,
+ "count": len(flat),
+ })
+}
diff --git a/handlers.go b/handlers.go
index 1a42258a..b37d92ff 100644
--- a/handlers.go
+++ b/handlers.go
@@ -45,108 +45,6 @@ func (b *Bridge) handleTabs(w http.ResponseWriter, r *http.Request) {
jsonResp(w, 200, map[string]any{"tabs": tabs})
}
-// ── GET /snapshot ──────────────────────────────────────────
-
-func (b *Bridge) handleSnapshot(w http.ResponseWriter, r *http.Request) {
- tabID := r.URL.Query().Get("tabId")
- filter := r.URL.Query().Get("filter")
- doDiff := r.URL.Query().Get("diff") == "true"
- format := r.URL.Query().Get("format") // "text" for indented tree
- maxDepthStr := r.URL.Query().Get("depth")
- maxDepth := -1
- if maxDepthStr != "" {
- if d, err := strconv.Atoi(maxDepthStr); err == nil {
- maxDepth = d
- }
- }
-
- ctx, resolvedTabID, err := b.TabContext(tabID)
- if err != nil {
- jsonErr(w, 404, err)
- return
- }
-
- tCtx, tCancel := context.WithTimeout(ctx, actionTimeout)
- defer tCancel()
- go cancelOnClientDone(r.Context(), tCancel)
-
- var rawResult json.RawMessage
- if err := chromedp.Run(tCtx,
- chromedp.ActionFunc(func(ctx context.Context) error {
- return chromedp.FromContext(ctx).Target.Execute(ctx,
- "Accessibility.getFullAXTree", nil, &rawResult)
- }),
- ); err != nil {
- jsonErr(w, 500, fmt.Errorf("a11y tree: %w", err))
- return
- }
-
- var treeResp struct {
- Nodes []rawAXNode `json:"nodes"`
- }
- if err := json.Unmarshal(rawResult, &treeResp); err != nil {
- jsonErr(w, 500, fmt.Errorf("parse a11y tree: %w", err))
- return
- }
-
- flat, refs := buildSnapshot(treeResp.Nodes, filter, maxDepth)
-
- // Get previous snapshot for diff before overwriting cache
- var prevNodes []A11yNode
- if doDiff {
- b.mu.RLock()
- if prev := b.snapshots[resolvedTabID]; prev != nil {
- prevNodes = prev.nodes
- }
- b.mu.RUnlock()
- }
-
- // Cache ref→nodeID mapping and nodes for this tab
- b.mu.Lock()
- b.snapshots[resolvedTabID] = &refCache{refs: refs, nodes: flat}
- b.mu.Unlock()
-
- var url, title string
- _ = chromedp.Run(tCtx,
- chromedp.Location(&url),
- chromedp.Title(&title),
- )
-
- if doDiff && prevNodes != nil {
- added, changed, removed := diffSnapshot(prevNodes, flat)
- jsonResp(w, 200, map[string]any{
- "url": url,
- "title": title,
- "diff": true,
- "added": added,
- "changed": changed,
- "removed": removed,
- "counts": map[string]int{
- "added": len(added),
- "changed": len(changed),
- "removed": len(removed),
- "total": len(flat),
- },
- })
- return
- }
-
- if format == "text" {
- w.Header().Set("Content-Type", "text/plain; charset=utf-8")
- w.WriteHeader(200)
- _, _ = fmt.Fprintf(w, "# %s\n# %s\n# %d nodes\n\n", title, url, len(flat))
- _, _ = w.Write([]byte(formatSnapshotText(flat)))
- return
- }
-
- jsonResp(w, 200, map[string]any{
- "url": url,
- "title": title,
- "nodes": flat,
- "count": len(flat),
- })
-}
-
// ── GET /screenshot ────────────────────────────────────────
func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
@@ -202,6 +100,7 @@ func (b *Bridge) handleScreenshot(w http.ResponseWriter, r *http.Request) {
func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
tabID := r.URL.Query().Get("tabId")
+ mode := r.URL.Query().Get("mode") // "raw" for innerText, default "clean"
ctx, _, err := b.TabContext(tabID)
if err != nil {
@@ -214,11 +113,21 @@ func (b *Bridge) handleText(w http.ResponseWriter, r *http.Request) {
go cancelOnClientDone(r.Context(), tCancel)
var text string
- if err := chromedp.Run(tCtx,
- chromedp.Evaluate(`document.body.innerText`, &text),
- ); err != nil {
- jsonErr(w, 500, fmt.Errorf("text extract: %w", err))
- return
+ if mode == "raw" {
+ if err := chromedp.Run(tCtx,
+ chromedp.Evaluate(`document.body.innerText`, &text),
+ ); err != nil {
+ jsonErr(w, 500, fmt.Errorf("text extract: %w", err))
+ return
+ }
+ } else {
+ // Clean extraction: strip nav/footer/aside/header, keep article/main content
+ if err := chromedp.Run(tCtx,
+ chromedp.Evaluate(readabilityJS, &text),
+ ); err != nil {
+ jsonErr(w, 500, fmt.Errorf("text extract: %w", err))
+ return
+ }
}
var url, title string
diff --git a/main.go b/main.go
index 51413e5b..a94c2143 100644
--- a/main.go
+++ b/main.go
@@ -39,7 +39,8 @@ func main() {
chromedp.NoDefaultBrowserCheck,
// Stealth: hide automation indicators
- chromedp.Flag("disable-blink-features", "AutomationControlled"),
+ // Note: --disable-blink-features=AutomationControlled removed — deprecated
+ // in Chrome 144+, triggers warning banner. stealth.js handles navigator.webdriver.
chromedp.Flag("exclude-switches", "enable-automation"),
chromedp.Flag("disable-infobars", true),
diff --git a/readability.js b/readability.js
new file mode 100644
index 00000000..23d44e2e
--- /dev/null
+++ b/readability.js
@@ -0,0 +1,28 @@
+// Lightweight readability extraction — strips nav/footer/aside/ads,
+// prefers article/main content, falls back to body.innerText.
+(() => {
+ const strip = ['nav', 'footer', 'aside', 'header', '[role="navigation"]',
+ '[role="banner"]', '[role="contentinfo"]', '[aria-hidden="true"]',
+ '.ad', '.ads', '.advertisement', '.sidebar', '.cookie-banner',
+ '#cookie-consent', '.popup', '.modal'];
+
+ // Try article or main first
+ let root = document.querySelector('article') ||
+ document.querySelector('[role="main"]') ||
+ document.querySelector('main');
+
+ if (!root) {
+ // Clone body and strip junk
+ root = document.body.cloneNode(true);
+ for (const sel of strip) {
+ root.querySelectorAll(sel).forEach(el => el.remove());
+ }
+ } else {
+ root = root.cloneNode(true);
+ }
+
+ // Clean up: remove scripts, styles, hidden elements
+ root.querySelectorAll('script, style, noscript, svg, [hidden]').forEach(el => el.remove());
+
+ return root.innerText.replace(/\n{3,}/g, '\n\n').trim();
+})()