Session and state management
Always use your own session
Pass-s <id> to all commands. Using the same session preserves your state between calls:
Store your own page in state
Pages are shared across all sessions. Create your own page to avoid interference:Handle page closures gracefully
Users may close tabs accidentally. Check before using:Interaction feedback loop
Every browser interaction should follow an observe → act → observe loop:- Observe - Print URL and take snapshot
- Check - Verify page is ready
- Act - Perform one action
- Observe again - Verify the action’s effect
- Repeat - Continue until task is complete
Quoting and escaping
Always use single quotes for -e
Single quotes prevent bash from interpreting$, backticks, and backslashes:
Use heredoc for complex code
When code contains mixed quotes, regex, or multiple lines:Choosing the right observation method
Use snapshot for most cases
Snapshots are fast, cheap, and text-based:Use screenshot only for visual issues
Screenshots consume more tokens and are slower:Reserve page.evaluate for specific use cases
Don’t usepage.evaluate() to inspect the DOM - use snapshot() instead:
Multiple execute calls vs single call
Use multiple execute calls for complex logic - it helps understand intermediate state:Waiting and timeouts
Prefer proper waits over arbitrary timeouts
Use waitForLoadState correctly
Selector best practices
Use snapshot locators directly
The snapshot output gives you ready-to-use locators:Beware CSS text-transform
Snapshots show visual text, but DOM may differ:Clean up listeners
Always remove event listeners when done:Navigation best practices
Use domcontentloaded for goto
Always print URL after actions
Pages can redirect unexpectedly:Common patterns
Network interception
Store requests in state for analysis:Authenticated fetches
Fetch from within page context to include session cookies:Working with iframes
Things to avoid
Never close browser or context
Never use bringToFront unless requested
Never use force clicks or dispatchEvent
Never use newCDPSession directly
Debugging
When something doesn’t work:- Print URL - Confirm you’re on the right page
- Take snapshot - See what’s actually there
- Check logs - Look for console errors