Skip to content

[feat]: add locator.filter() - #3567

Merged
seanmcguire12 merged 4 commits into
mainfrom
locator-text-filters
Nov 25, 2026
Merged

seanmcguire12 merged 4 commits into
mainfrom
locator-text-filters

Conversation

@seanmcguire12

@seanmcguire12 seanmcguire12 commented Nov 25, 2026 •

Copy link
Copy Markdown
Member

why

this pr adds Locator.filter(), which allows for filtering matches by text

const billing = page.locator(".card").filter({ hasText: "Billing", hasNotText: "Archived" });
await billing.first().locator("button").click();
billing = page.locator(".card").filter(has_text="Billing", has_not_text="Archived")
await billing.first().locator("button").click()

what changed

  • added typed inclusion & exclusion filters with case-insensitive, whitespace-normalized substring matching. both conditions must pass when supplied together.
  • filters match text within each element, including its descendants & open/closed shadow roots, while retaining the original elements in order. filtering an iframe does not search its child document.
  • filter/index order is preserved, & filtering creates a new locator without changing the original. .nth(1).filter(...) tests the second original match; .filter(...).nth(1) selects the second surviving match.
  • each filter runs in one page-side call per participating document. counts avoid exporting final element handles, & temporary handles use grouped cleanup.
  • empty filters retain all matches, empty hasText retains all, & empty hasNotText retains none. unsupported options & non-string matchers are rejected before dispatch; python uses None to omit a condition.

test plan

added & extended tests covering:

  • shared wire fixtures, public types, supported options, invalid matchers, unknown fields, & null rejection in python wire models during construction & assignment.
  • lazy construction, independent branches, filter/index order, request serialization, & following queries.
  • simultaneous inclusion/exclusion, normalized text, empty strings, no matches, original element identity, & refreshed results after text changes.
  • public counts & clicks in both sdks, explicit iframe entry, nested/cross-origin frames, & open/closed shadow roots.
  • mixed-document ordering, overlapping scopes, & count/selected/all result modes.

Summary by cubic

Adds Locator.filter() for narrowing element matches by text without changing the original locator.

  • New filter({ hasText, hasNotText }) option takes case-insensitive, whitespace-normalized substring conditions; both conditions must pass when supplied together.
  • Filtering is lazy, keeps original element identity and order, and composes with existing nth() and query steps.
  • Text extraction matches getByText() including descendants and open/closed shadow roots; filtering an iframe does not enter its child document.
  • Unsupported options like regular expressions, has, hasNot, and exact fail during construction, before any browser request.

Migration

  • locator.filter({ ... }) and locator.filter(has_text=..., has_not_text=...) accept string-only matchers; use None (Python) or omit the option (TypeScript) to skip a condition.

Written for commit cb756a7. Summary will update on new commits.

View guided diff Turn on auto-fix

@seanmcguire12
seanmcguire12 requested a review from a team as a code owner November 25, 2026 22:05
@seanmcguire12
seanmcguire12 removed the request for review from a team November 25, 2026 22:06
@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: cb756a7

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 19 packages
Name Type
@browserbasehq/stagehand-python Minor
@browserbasehq/stagehand-extension Minor
@browserbasehq/stagehand-protocol Minor
@browserbasehq/stagehand Minor
@browserbasehq/stagehand-examples Patch
@browserbasehq/stagehand-integrations-claude-cua-sdk Patch
@browserbasehq/stagehand-integrations Patch
@browserbasehq/eve Patch
@browserbasehq/stagehand-integrations-gemini-cua-sdk Patch
@browserbasehq/stagehand-integrations-example-pi-facade Patch
@browserbasehq/stagehand-integrations-claude-code Patch
@browserbasehq/stagehand-integrations-codex Patch
@browserbasehq/stagehand-integrations-cursor Patch
@browserbasehq/stagehand-integrations-deepagents-sdk Patch
@browserbasehq/stagehand-integrations-fx Patch
@browserbasehq/stagehand-integrations-mastra Patch
@browserbasehq/stagehand-integrations-pi-sdk Patch
@browserbasehq/stagehand-integrations-example-vercel-ai-facade Patch
@browserbasehq/stagehand-integrations-eve-harness Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 28 files

Architecture diagram
sequenceDiagram
    participant SDK as SDK (TS/Python)
    participant Protocol as Protocol Schemas/Validation
    participant API as Browser API (Locator engine)
    participant Chain as Chain Resolver (Understudy)
    participant DOM as DOM Extension (Frame Chain)
    participant Browser as Browser/CDP

    Note over SDK,Protocol: Locator.filter() API construction

    SDK->>SDK: filter({hasText, hasNotText}) or filter(has_text, has_not_text)
    SDK->>Protocol: Build LocatorFilterStep
    Protocol->>Protocol: Validate options (string-only, no regex/has/exact)
    
    alt Invalid options (regex, null in Python, has/hasNot, exact)
        Protocol-->>SDK: Throw validation error before dispatch
    else Valid options
        SDK->>API: appendSteps([{type:"filter", ...options}])
        API->>API: Store as new lazy locator (doesn't mutate original)
    end

    Note over API,Chain: Chain resolution with filter step (lazy, on action/count)

    API->>Chain: resolve(chain, {mode: "count"/"selected"/"all"})
    Chain->>Chain: Walk steps in order (query, frame, nth, filter)
    
    alt Maintenance chain includes filter step
        Chain->>DOM: this.filter(options, selectedIds)
        DOM->>DOM: filterTextMatches(candidates, options)
        DOM->>DOM: Create text matcher with normalization (case-insensitive, whitespace, zero-width removal)
        DOM->>DOM: Include/exclude based on hasText/hasNotText (both must pass)
        DOM-->>Chain: Return retained element IDs (original order/dedup)
    end

    alt Frame chain includes filter step (iframes/cross-origin)
        Chain->>Chain: groupByWorld(matches)
        Chain->>Browser: Runtime.callFunctionOn per world (filter options, IDs)
        Browser->>Browser: Execute this.filter(options, ids) per document
        Browser-->>Chain: Return filtered IDs per world
        Chain->>Chain: Merge results preserving original order
    end

    Note over Chain,Browser: Filter semantics

    opt Filtering iframe element
        DOM->>DOM: Test iframe's own DOM text only (NOT child document)
    end

    opt Shadow DOM (open/closed)
        DOM->>DOM: Extract text from shadow roots (closed needs http/https)
    end

    Chain-->>API: Resolved elements (IDs kept, no handles exported for count)
    API-->>SDK: Return count/selected/all result

    Note over API,SDK: Text updates cause re-evaluation on next action

    SDK->>API: count()/click()/locator() after filter
    API->>Chain: Re-resolve chain (fresh filter evaluation)
    DOM->>DOM: Re-run filterTextMatches on current DOM text
    DOM-->>Chain: Updated filtered set
    Chain-->>API: New results (e.g., count now 0 if text changed)
Loading

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment thread .changeset/common-turkeys-occur.md Resolved

Filtering an iframe tests the iframe element's own DOM text and does not enter its child document. Use `page.locator("iframe").locator(".card").filter({ hasText: "Billing" })` to filter cards inside it. Closed shadow-root traversal requires an `http:` or `https:` page.

`filter()` and `filter({})` retain all current matches. An empty `hasText` retains all matches; an empty `hasNotText` retains none. Regular expressions, `has`, `hasNot`, and exact matching are unsupported. Invalid options fail during construction, before a browser request.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: the docs say an empty hasNotText retains none, but whitespace-only values behave the same after normalization: in Chrome " ", "\n" and a lone zero-width space each dropped every match. Could this say "empty or whitespace-only" (same line at 1208 for Python)? Playwright ignores an empty hasNotText, so a note on that difference would help people porting code.

[claude-opus-5-5, /auto-review, severity 3/10]

const secondCardIfBilling = cards.nth(1).filter({ hasText: "Billing" });
```

Matching uses case-insensitive substrings. It removes zero-width spaces (`U+200B`) and soft hyphens (`U+00AD`), then trims and collapses whitespace in both the filter and element text. Text extraction follows `getByText()`, including descendant text, button input values, and open/closed shadow roots. Hidden text is included. The filter retains each original element, rather than selecting its smallest matching descendant.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: filter reads text the way getByText() does, so anything in <head> or a <template> reads as empty. In Chrome locator("title").filter({ hasText: "Save" }) matched nothing on a page titled "Save title", and hasNotText kept it. Worth one line next to "Hidden text is included".

[claude-opus-5-5, /auto-review, severity 2/10]

);
},
filter(options: LocatorFilterStep, selected: number[]): number[] {
return filterTextMatches(this.elements(selected), options).map((node) => ids.get(node)!);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: filter() goes through this.elements(selected), which throws "Chain iframe detached before entry" for a detached iframe but lets a detached div through to be filtered on its stale text. Nothing retries that error. Is the difference intended, or should filter skip the entry guard?

[claude-opus-5-5, /auto-review, severity 3/10]

if (step.type === "nth") {
const selected = matches[step.index];
matches = selected ? [selected] : [];
} else if (step.type === "filter") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

question: this branch, and the filter-ordering tests in elementChainResolution.test.ts, run through resolveElementChain, which only FrameElementChainResolver calls, and nothing outside tests constructs that class. Is the element resolver still a supported path? If not, the assertions could move onto FrameChainResolver and this branch could go.

[claude-opus-5-5, /auto-review, severity 3/10]

@seanmcguire12
seanmcguire12 merged commit 97ff3e1 into main Nov 25, 2026
68 checks passed
@seanmcguire12
seanmcguire12 deleted the locator-text-filters branch November 25, 2026 23:24
cursor Bot pushed a commit that referenced this pull request Nov 26, 2026
Merge origin/main into cursor/fix-remote-session-status-propagation-38a5

Conflicts resolved:
- packages/cli/src/lib/driver/remote.ts: Keep PR's extractHttpStatus/extractUpstreamMessage helpers for cause chain extraction and 402/429 handling, incorporate main's removal of redundant JSDoc comments
- packages/cli/src/lib/driver/remote.disabled.ts: Keep PR's extractHttpStatus function for consistent httpStatus extraction in disabled stub

Changes from main:
- locator.filter() feature (#3567)
- page-level error classification (#3515)
- bare hostname URL fix (#3512)
- comment removal cleanup (#3538)
- other SDK and CLI improvements

Co-authored-by: Shrey Pandya <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants