Automation
How to solve CAPTCHAs in Playwright
CT
CaptchaSonic Team
Automation & Web Scraping
Playwright is great for scraping and end-to-end tests — until a reCAPTCHA or Turnstile challenge blocks the flow. This guide covers the clean fix: get a fresh token from CaptchaSonic over gRPC and inject it, so the page proceeds as if a human solved the challenge.
TIP
This is the token flow. The playwright-solver
repo also ships a script solver (ScriptSolver) for challenges you'd rather solve in-page.
Install
npm install captchasonic playwright
npx playwright install chromium
export CAPTCHASONIC_API_KEY=sonic_your_key_here # dashboard → API Keys
The core flow
import { chromium } from 'playwright';
import { CaptchaSonic } from 'captchasonic';
const client = new CaptchaSonic(process.env.CAPTCHASONIC_API_KEY);
const browser = await chromium.launch({ headless: true });
const page = await browser.newPage();
await page.goto('https://example.com/login');
// 1. Read the sitekey from the page.
const sitekey = await page.getAttribute('[data-sitekey]', 'data-sitekey');
// 2. Solve over gRPC (auto-polls, returns when ready).
const result = await client.solveRecaptchaV2Token({
websiteURL: page.url(),
websiteKey: sitekey,
});
const token = result.solution.gRecaptchaResponse;
// 3. Inject the token and submit.
await page.evaluate((t) => {
document.querySelector('#g-recaptcha-response').value = t;
}, token);
await page.click('button[type="submit"]');
await browser.close();
The transport is invisible — one typed method call returns the token, and the SDK handles polling and retries for you.
Handling the tricky cases
- Callback-bound tokens. If the site uses
data-callback, call it directly:await page.evaluate((t) => window.onCaptcha(t), token). - Solve late. reCAPTCHA tokens expire in ~120 s — solve right before you submit.
- Read sitekeys at runtime. Grab
data-sitekeyfrom the live DOM instead of hard-coding it. - Cross-browser. The same code runs on
firefoxandwebkit— just swap the launcher. - IP coherence. Pass a
proxyoption when the target validates the solving IP against the submitting IP.
Beyond reCAPTCHA
Swap the method to solve Cloudflare Turnstile, GeeTest, AWS WAF, or image captchas — see the Node.js SDK reference for the full set.
Next steps
- The step-by-step Playwright integration doc
- The Recipe: reCAPTCHA in Playwright end-to-end login flow
- The playwright-solver example repo