1---2name: core-browser-automation-23description: General-purpose patterns for reliable browser automation (selectors, waiting, scrolling, overlays, HITL).4---5
6## Selector Strategy (Stability First)
7- **Priority 1**: `data-testid`, `data-test`, `data-cy`, `id` (if stable).
8- **Priority 2**: Accessible roles with names (e.g., `getByRole('button', { name: 'Submit' })`).
9- **Priority 3**: Text content (e.g., `getByText('Submit')`) - use with caution if text is dynamic.
10- **Avoid**: Brittle CSS selectors (e.g., `div > div:nth-child(3)`), XPath, or selectors tied to visual layout.
11
12## Waiting Strategy (No Flaky Sleeps)
13- **Explicit Waits**: Wait for elements to be **attached**, **visible**, and **enabled** before interacting.
14- **State Changes**: Wait for clear UI signals (spinners disappearing, success messages appearing).
15- **Bounded Polling**: If no clear signal exists, use a loop with a short sleep (1-2s) and a max retry count.
16- **Avoid**: Long blind sleeps (e.g., `sleep(5000)`).
17
18## Scroll Strategy
19- **Window vs. Container**: Determine if the scrollbar belongs to the `window` or a specific container element.
20- **Incremental Scan**: Scroll in small chunks (e.g., half viewport) to trigger lazy-loading or reveal elements.
21- **Check after Scroll**: Re-evaluate the page state after scrolling (elements might become visible).
22
23## Handling Overlays & Modals
24- **Detection**: Watch for common overlay selectors (dialogs, cookie banners, "interstitial" layers).
25- **Dismissal**: Look for "Close", "X", "Accept", "Reject", "No thanks" buttons.
26- **Click Intercepted**: If a click fails due to an overlay, find the overlay, dismiss it, and retry the click.
27
28## Frames & Iframes
29- **Detection**: If an element is not found, check if it resides within an `iframe`.
30- **Switching**: Switch context to the iframe before querying elements inside it.
31
32## Human-in-the-Loop (HITL) Policy
33- **Auth**: Stop for Login/SSO/MFA/CAPTCHA. Ask user to complete and type "Done".
34- **Irreversible Actions**: **ALWAYS** ask for explicit confirmation before clicking:
35 - Submit / Complete / Finish
36 - Attest / Certify
37 - Approve / Confirm / Yes
38 - Send / Pay
39- **Ambiguity**: If unsure if an action is irreversible, ASK first.
40
41## Recovery Rules
42- **Element not found**:
43 - Check for iframes.
44 - Check for shadow DOM.
45 - Check if the element is behind an overlay.
46 - Scroll to bring it into view.
47- **Click intercepted**:
48 - Identify the obscuring element.
49 - Dismiss it (if it's a modal/banner).
50 - Wait for it to disappear (if it's a toast/spinner).
51- **Stale element**:
52 - Re-query the element from the DOM before interacting.