Skip to content

Browser automation

These pages are for scripts and AI agents that drive a real browser - for testing your own sites, automating your own workflows, or collecting data from sites you are allowed to access - and meet a captcha on the way. Using NoptCHA there always takes the same four steps:

  1. Read the parameters of the captcha from the page: its type, the site key, and for some types an action or extra data.
  2. Solve the task with the native API (v1): POST /v1/tasks with Prefer: wait=60 returns the token, usually in one request.
  3. Put the token back where the page’s own code looks for it: a hidden response field, a callback function, or the widget’s JavaScript API.
  4. Submit the form (or continue the flow) as usual.

Steps 1 and 3 are JavaScript that runs in the page, so they are the same in every framework. The helper modules on this page contain them, plus a small HTTP client for step 2. The framework pages show the few lines that connect them to each tool:

The parameters below are what the task types need. website_url is always the address of the page that shows the captcha (location.href).

Captcha Task type Read from the page
reCAPTCHA v2 recaptcha.v2 website_key: data-sitekey of the .g-recaptcha element, or k= in the URL of the …/recaptcha/api2/anchor iframe. is_invisible: data-size="invisible" or size=invisible in that URL. api_domain: only when the widget loads from www.recaptcha.net
reCAPTCHA v3 recaptcha.v3 website_key: render= in the URL of api.js. page_action: the action the site passes to grecaptcha.execute(key, { action }) - look for it in the site’s scripts
reCAPTCHA Enterprise recaptcha.v2.enterprise, recaptcha.v3.enterprise As above; the page loads enterprise.js instead of api.js. A data-s attribute goes into enterprise_payload as { "s": … }
hCaptcha hcaptcha website_key: data-sitekey of the .h-captcha element, or sitekey= in the fragment of the widget’s iframe URL. is_invisible: data-size="invisible"
Turnstile turnstile website_key, action, cdata: data-sitekey, data-action, data-cdata of the .cf-turnstile element
FunCaptcha funcaptcha website_public_key: data-pkey, the key in the script URL …/v2/<public key>/api.js, or pk= in the value of the fc-token field. api_subdomain: the host that serves that api.js (surl= in fc-token)

When a site renders the widget from its own script (grecaptcha.render(el, { sitekey }), turnstile.render(…), hcaptcha.render(…)), the same values are in that call. If the widget sits inside an iframe of the page, run the page script in that frame.

Captcha Where the site reads the token
reCAPTCHA v2, Enterprise The g-recaptcha-response textarea in the form; the function named in data-callback, or the callback passed to grecaptcha.render (kept in ___grecaptcha_cfg)
reCAPTCHA v3 Usually nothing on the page: the site calls grecaptcha.execute() when the form is submitted. Make execute (and grecaptcha.enterprise.execute) resolve with the token, then submit
hCaptcha The h-captcha-response and g-recaptcha-response textareas; the data-callback function; hcaptcha.getResponse()
Turnstile The cf-turnstile-response hidden input (or the name in data-response-field-name); the data-callback function; turnstile.getResponse()
FunCaptcha The fc-token or verification-token field; the onCompleted callback the site passes to setConfig() from the setup function named in the data-callback of its api.js script, called with { token }

Tokens expire after a couple of minutes, so solve right before you submit. The solution may also carry a user_agent; if the site checks it, send the token from a browser with that user agent.

findCaptchas / FIND_JS returns every captcha the page shows as [{ type, params }], ready for POST /v1/tasks. putToken / PUT_JS does what the second table says for the given type and returns what it did. solve() creates the task with an idempotency key (so a retry never creates a second task), waits for it and returns task.solution, or raises CaptchaError with the task’s error code (failed tasks are not charged). solveOnPage / solve_on_page does all three for the first captcha on the page.

Both read the key from the NOPTCHA_KEY environment variable; NOPTCHA_KEY=keyless uses the keyless sandbox (/v1/sandbox/tasks, no key sent). Keep the key in your script’s environment; never put it into the page.

noptcha_browser.py
"""noptcha_browser.py: find a captcha on a page, solve it with the Noptcha v1 API, put the token back.
Python 3 and requests. Reads the key from NOPTCHA_KEY: a nop_test_ key runs in the sandbox and returns a fixed
test token, so you can wire this up before you spend anything. NOPTCHA_KEY=keyless uses the keyless sandbox
(/v1/sandbox/tasks, no account needed, limited per IP) with the same fixed answers. Works with any framework that
can run JavaScript in the page: FIND_JS and PUT_JS are JavaScript functions, solve() is plain HTTP.
"""
import os
import time
import uuid
import requests
API = "https://api.noptcha.com"
# Runs in the page: returns [{type, params}] for every captcha it recognizes. `type` is a Noptcha task type,
# `params` its parameters as read from the page.
FIND_JS = r"""() => {
const found = [];
const seen = new Set();
const all = (sel) => Array.from(document.querySelectorAll(sel));
const arg = (src, name) => {
try {
const u = new URL(src, location.href);
return u.searchParams.get(name) || new URLSearchParams(u.hash.slice(1)).get(name);
} catch {
return null;
}
};
const add = (type, params) => {
const id = type.split('.')[0] + ':' + params.website_key + params.website_public_key;
if (seen.has(id)) return;
seen.add(id);
for (const k of Object.keys(params)) if (params[k] === undefined || params[k] === null || params[k] === false) delete params[k];
found.push({ type, params: { website_url: location.href, ...params } });
};
const scripts = all('script[src]').map((s) => s.src);
const inline = all('script:not([src])').map((s) => s.textContent).join('\n');
// reCAPTCHA: v3 is loaded with ?render=<site key>; v2 is a .g-recaptcha element or an anchor iframe
const rcScripts = scripts.filter((s) => /\/recaptcha\/(api|enterprise)\.js/.test(s));
const rcEnterprise = rcScripts.some((s) => s.includes('/enterprise.js')) || all('iframe[src*="/recaptcha/enterprise/"]').length > 0;
const rcHost = [...rcScripts, ...all('iframe[src*="/recaptcha/"]').map((f) => f.src)].map((s) => new URL(s, location.href).hostname)[0];
const apiDomain = rcHost && rcHost !== 'www.google.com' && rcHost.includes('recaptcha') ? rcHost : undefined;
const action = (inline.match(/\.execute\(\s*[^,()]+,\s*\{\s*action\s*:\s*['"]([^'"]+)['"]/) || [])[1];
for (const s of rcScripts) {
const key = arg(s, 'render');
if (key && key !== 'explicit' && key !== 'onload') {
add(rcEnterprise ? 'recaptcha.v3.enterprise' : 'recaptcha.v3', { website_key: key, page_action: action, api_domain: apiDomain });
}
}
const v2 = rcEnterprise ? 'recaptcha.v2.enterprise' : 'recaptcha.v2';
for (const el of all('.g-recaptcha[data-sitekey]')) {
const s = el.getAttribute('data-s');
add(v2, {
website_key: el.getAttribute('data-sitekey'),
is_invisible: el.getAttribute('data-size') === 'invisible',
enterprise_payload: rcEnterprise && s ? { s } : undefined,
api_domain: apiDomain,
});
}
for (const f of all('iframe[src*="/recaptcha/api2/anchor"], iframe[src*="/recaptcha/enterprise/anchor"]')) {
if (arg(f.src, 'k')) add(v2, { website_key: arg(f.src, 'k'), is_invisible: arg(f.src, 'size') === 'invisible', api_domain: apiDomain });
}
// hCaptcha: an .h-captcha element, or its iframe (site key in the fragment)
for (const el of all('.h-captcha[data-sitekey]')) {
add('hcaptcha', { website_key: el.getAttribute('data-sitekey'), is_invisible: el.getAttribute('data-size') === 'invisible' });
}
for (const f of all('iframe[src*="hcaptcha"]')) {
if (arg(f.src, 'sitekey')) add('hcaptcha', { website_key: arg(f.src, 'sitekey') });
}
// Turnstile: a .cf-turnstile element with data-sitekey, data-action, data-cdata
for (const el of all('.cf-turnstile[data-sitekey]')) {
add('turnstile', {
website_key: el.getAttribute('data-sitekey'),
action: el.getAttribute('data-action'),
cdata: el.getAttribute('data-cdata'),
});
}
// FunCaptcha: data-pkey, the api.js script (/v2/<public key>/api.js on the widget's host), or the fc-token field
for (const el of all('[data-pkey]')) add('funcaptcha', { website_public_key: el.getAttribute('data-pkey') });
for (const s of scripts) {
const m = s.match(/\/v2\/([0-9A-Fa-f-]{36})\/api\.js/);
if (m) add('funcaptcha', { website_public_key: m[1], api_subdomain: new URL(s).hostname });
}
for (const el of all('input[name="fc-token"]')) {
const v = Object.fromEntries(el.value.split('|').map((p) => p.split('=')));
const surl = v.surl ? decodeURIComponent(v.surl) : '';
if (v.pk) add('funcaptcha', { website_public_key: v.pk, api_subdomain: surl ? new URL(surl).hostname : undefined });
}
return found;
}"""
# Runs in the page with {type, token}: puts the token where the site reads it (the response field, the widget's
# callback, the widget's getResponse/execute) and returns what it did. The form is not submitted.
PUT_JS = r"""({ type, token }) => {
const did = [];
const family = type.split('.')[0];
const lookup = (name) => name.split('.').reduce((o, k) => (o == null ? o : o[k]), window);
const call = (fn, label, value) => {
const f = typeof fn === 'string' ? lookup(fn) : fn;
if (typeof f !== 'function') return false;
f(value);
did.push('callback ' + label);
return true;
};
// the response field, created next to the widget when the page has none yet
const fill = (name, widgetSel) => {
let els = Array.from(document.querySelectorAll('[name="' + name + '"]'));
const widget = document.querySelector(widgetSel);
if (!els.length && widget) {
const t = document.createElement('textarea');
t.name = name;
t.style.display = 'none';
widget.appendChild(t);
els = [t];
}
for (const el of els) {
el.value = token;
if (el.tagName === 'TEXTAREA') el.textContent = token;
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
}
if (els.length) did.push(name);
};
const callbacks = (sel) => {
let n = 0;
for (const el of document.querySelectorAll(sel)) if (call(el.getAttribute('data-callback'), el.getAttribute('data-callback'), token)) n++;
return n;
};
if (family === 'recaptcha') {
fill('g-recaptcha-response', '.g-recaptcha');
const g = window.grecaptcha;
if (type.startsWith('recaptcha.v3') && g) {
// v3: the site asks grecaptcha.execute() for a token when it submits; answer with this one
for (const o of [g, g.enterprise]) if (o) o.execute = () => Promise.resolve(token);
did.push('grecaptcha.execute');
}
if (!callbacks('.g-recaptcha[data-callback]')) {
// widgets rendered with grecaptcha.render(el, { callback }) keep the callback in ___grecaptcha_cfg
const seen = new Set();
const walk = (o, depth) => {
if (!o || typeof o !== 'object' || depth > 5 || seen.has(o)) return;
seen.add(o);
for (const [k, v] of Object.entries(o)) {
if (k === 'callback' && call(v, 'from grecaptcha.render', token)) return;
walk(v, depth + 1);
}
};
for (const client of Object.values((window.___grecaptcha_cfg || {}).clients || {})) walk(client, 0);
}
} else if (family === 'hcaptcha') {
fill('h-captcha-response', '.h-captcha');
fill('g-recaptcha-response', '.h-captcha');
if (window.hcaptcha) window.hcaptcha.getResponse = () => token;
callbacks('.h-captcha[data-callback]');
} else if (family === 'turnstile') {
const el = document.querySelector('.cf-turnstile');
fill((el && el.getAttribute('data-response-field-name')) || 'cf-turnstile-response', '.cf-turnstile');
if (window.turnstile) window.turnstile.getResponse = () => token;
callbacks('.cf-turnstile[data-callback]');
} else if (family === 'funcaptcha') {
for (const name of ['fc-token', 'verification-token']) if (document.querySelector('[name="' + name + '"]')) fill(name, 'body');
// the api.js script names a setup function (data-callback) that passes { onCompleted } to setConfig();
// call it again with a stand-in object to get onCompleted, then complete with the token
for (const s of document.querySelectorAll('script[data-callback]')) {
if (!/\/v2\/[0-9A-Fa-f-]{36}\/api\.js/.test(s.src)) continue;
let config = {};
const stub = new Proxy({}, { get: (_, k) => (k === 'setConfig' ? (c) => Object.assign(config, c) : () => {}) });
call(s.getAttribute('data-callback'), 'setup', stub);
call(config.onCompleted, 'onCompleted', { token });
}
}
return did;
}"""
class CaptchaError(Exception):
"""The task failed: unsolvable, timeout, proxy_error, ... (failed tasks are not charged)."""
def __init__(self, code, task_id):
super().__init__(f"task {task_id} failed: {code}")
self.code = code
self.task_id = task_id
def _call(session, method, path, **kwargs):
for attempt in range(4):
try:
r = session.request(method, API + path, timeout=100, **kwargs)
except requests.ConnectionError:
if attempt == 3:
raise
else:
if r.status_code not in (409, 429) and r.status_code < 500:
if not r.ok: # problem+json
p = r.json()
raise RuntimeError(f"{r.status_code} {p.get('code')}: {p.get('detail') or p.get('title')}")
return r.json()
if attempt == 3:
r.raise_for_status()
if r.headers.get("Retry-After", "").isdigit():
time.sleep(min(int(r.headers["Retry-After"]), 30))
continue
time.sleep(2**attempt)
def solve(task_type, params, timeout=180):
"""Solve one captcha with the v1 API and return task["solution"] ({"token": ..., "user_agent": ...})."""
key = os.environ.get("NOPTCHA_KEY", "")
if not key:
raise RuntimeError("set NOPTCHA_KEY to a nop_test_ or nop_live_ key, or to 'keyless' for the keyless sandbox")
session = requests.Session()
tasks = "/v1/sandbox/tasks" if key == "keyless" else "/v1/tasks"
if key != "keyless":
session.headers["Authorization"] = f"Bearer {key}"
deadline = time.monotonic() + timeout
# one idempotency key per task: a retry of the create request returns the same task instead of a second one
headers = {"Prefer": "wait=60", "Idempotency-Key": str(uuid.uuid4())}
task = _call(session, "POST", tasks, headers=headers, json={"type": task_type, "params": params})
while task["status"] not in ("solved", "failed"):
if time.monotonic() > deadline:
raise TimeoutError(f"task {task['id']} still {task['status']}")
task = _call(session, "GET", f"{tasks}/{task['id']}", params={"wait": 60})
if task["status"] == "failed":
raise CaptchaError(task["error"]["code"], task["id"])
return task["solution"]
def solve_on_page(evaluate):
"""Find the first captcha on the page, solve it and put the token back.
evaluate(js, arg=None) runs a JavaScript function in the page and returns its result: pass a small adapter for
your framework (see the integration pages). Returns None when the page has no captcha this helper recognizes,
else {"type", "params", "solution", "did"}.
"""
found = evaluate(FIND_JS)
if not found:
return None
captcha = found[0]
solution = solve(captcha["type"], captcha["params"])
did = evaluate(PUT_JS, {"type": captcha["type"], "token": solution["token"]})
return {**captcha, "solution": solution, "did": did}
noptcha-browser.mjs
// noptcha-browser.mjs: find a captcha on a page, solve it with the Noptcha v1 API, put the token back.
// Node.js 22+ (built-in fetch); no dependencies. Reads the key from NOPTCHA_KEY: a nop_test_ key runs in the
// sandbox and returns a fixed test token, so you can wire this up before you spend anything. NOPTCHA_KEY=keyless
// uses the keyless sandbox (/v1/sandbox/tasks, no account needed, limited per IP) with the same fixed answers.
const API = 'https://api.noptcha.com';
// Runs in the page: returns [{ type, params }] for every captcha it recognizes. `type` is a Noptcha task type,
// `params` its parameters as read from the page.
export const findCaptchas = () => {
const found = [];
const seen = new Set();
const all = (sel) => Array.from(document.querySelectorAll(sel));
const arg = (src, name) => {
try {
const u = new URL(src, location.href);
return u.searchParams.get(name) || new URLSearchParams(u.hash.slice(1)).get(name);
} catch {
return null;
}
};
const add = (type, params) => {
const id = type.split('.')[0] + ':' + params.website_key + params.website_public_key;
if (seen.has(id)) return;
seen.add(id);
for (const k of Object.keys(params)) if (params[k] === undefined || params[k] === null || params[k] === false) delete params[k];
found.push({ type, params: { website_url: location.href, ...params } });
};
const scripts = all('script[src]').map((s) => s.src);
const inline = all('script:not([src])').map((s) => s.textContent).join('\n');
// reCAPTCHA: v3 is loaded with ?render=<site key>; v2 is a .g-recaptcha element or an anchor iframe
const rcScripts = scripts.filter((s) => /\/recaptcha\/(api|enterprise)\.js/.test(s));
const rcEnterprise = rcScripts.some((s) => s.includes('/enterprise.js')) || all('iframe[src*="/recaptcha/enterprise/"]').length > 0;
const rcHost = [...rcScripts, ...all('iframe[src*="/recaptcha/"]').map((f) => f.src)].map((s) => new URL(s, location.href).hostname)[0];
const apiDomain = rcHost && rcHost !== 'www.google.com' && rcHost.includes('recaptcha') ? rcHost : undefined;
const action = (inline.match(/\.execute\(\s*[^,()]+,\s*\{\s*action\s*:\s*['"]([^'"]+)['"]/) || [])[1];
for (const s of rcScripts) {
const key = arg(s, 'render');
if (key && key !== 'explicit' && key !== 'onload') {
add(rcEnterprise ? 'recaptcha.v3.enterprise' : 'recaptcha.v3', { website_key: key, page_action: action, api_domain: apiDomain });
}
}
const v2 = rcEnterprise ? 'recaptcha.v2.enterprise' : 'recaptcha.v2';
for (const el of all('.g-recaptcha[data-sitekey]')) {
const s = el.getAttribute('data-s');
add(v2, {
website_key: el.getAttribute('data-sitekey'),
is_invisible: el.getAttribute('data-size') === 'invisible',
enterprise_payload: rcEnterprise && s ? { s } : undefined,
api_domain: apiDomain,
});
}
for (const f of all('iframe[src*="/recaptcha/api2/anchor"], iframe[src*="/recaptcha/enterprise/anchor"]')) {
if (arg(f.src, 'k')) add(v2, { website_key: arg(f.src, 'k'), is_invisible: arg(f.src, 'size') === 'invisible', api_domain: apiDomain });
}
// hCaptcha: an .h-captcha element, or its iframe (site key in the fragment)
for (const el of all('.h-captcha[data-sitekey]')) {
add('hcaptcha', { website_key: el.getAttribute('data-sitekey'), is_invisible: el.getAttribute('data-size') === 'invisible' });
}
for (const f of all('iframe[src*="hcaptcha"]')) {
if (arg(f.src, 'sitekey')) add('hcaptcha', { website_key: arg(f.src, 'sitekey') });
}
// Turnstile: a .cf-turnstile element with data-sitekey, data-action, data-cdata
for (const el of all('.cf-turnstile[data-sitekey]')) {
add('turnstile', {
website_key: el.getAttribute('data-sitekey'),
action: el.getAttribute('data-action'),
cdata: el.getAttribute('data-cdata'),
});
}
// FunCaptcha: data-pkey, the api.js script (/v2/<public key>/api.js on the widget's host), or the fc-token field
for (const el of all('[data-pkey]')) add('funcaptcha', { website_public_key: el.getAttribute('data-pkey') });
for (const s of scripts) {
const m = s.match(/\/v2\/([0-9A-Fa-f-]{36})\/api\.js/);
if (m) add('funcaptcha', { website_public_key: m[1], api_subdomain: new URL(s).hostname });
}
for (const el of all('input[name="fc-token"]')) {
const v = Object.fromEntries(el.value.split('|').map((p) => p.split('=')));
const surl = v.surl ? decodeURIComponent(v.surl) : '';
if (v.pk) add('funcaptcha', { website_public_key: v.pk, api_subdomain: surl ? new URL(surl).hostname : undefined });
}
return found;
};
// Runs in the page: puts the token where the site reads it (the response field, the widget's callback, the
// widget's getResponse/execute) and returns what it did. The form is not submitted.
export const putToken = ({ type, token }) => {
const did = [];
const family = type.split('.')[0];
const lookup = (name) => name.split('.').reduce((o, k) => (o == null ? o : o[k]), window);
const call = (fn, label, value) => {
const f = typeof fn === 'string' ? lookup(fn) : fn;
if (typeof f !== 'function') return false;
f(value);
did.push('callback ' + label);
return true;
};
// the response field, created next to the widget when the page has none yet
const fill = (name, widgetSel) => {
let els = Array.from(document.querySelectorAll('[name="' + name + '"]'));
const widget = document.querySelector(widgetSel);
if (!els.length && widget) {
const t = document.createElement('textarea');
t.name = name;
t.style.display = 'none';
widget.appendChild(t);
els = [t];
}
for (const el of els) {
el.value = token;
if (el.tagName === 'TEXTAREA') el.textContent = token;
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
}
if (els.length) did.push(name);
};
const callbacks = (sel) => {
let n = 0;
for (const el of document.querySelectorAll(sel)) if (call(el.getAttribute('data-callback'), el.getAttribute('data-callback'), token)) n++;
return n;
};
if (family === 'recaptcha') {
fill('g-recaptcha-response', '.g-recaptcha');
const g = window.grecaptcha;
if (type.startsWith('recaptcha.v3') && g) {
// v3: the site asks grecaptcha.execute() for a token when it submits; answer with this one
for (const o of [g, g.enterprise]) if (o) o.execute = () => Promise.resolve(token);
did.push('grecaptcha.execute');
}
if (!callbacks('.g-recaptcha[data-callback]')) {
// widgets rendered with grecaptcha.render(el, { callback }) keep the callback in ___grecaptcha_cfg
const seen = new Set();
const walk = (o, depth) => {
if (!o || typeof o !== 'object' || depth > 5 || seen.has(o)) return;
seen.add(o);
for (const [k, v] of Object.entries(o)) {
if (k === 'callback' && call(v, 'from grecaptcha.render', token)) return;
walk(v, depth + 1);
}
};
for (const client of Object.values((window.___grecaptcha_cfg || {}).clients || {})) walk(client, 0);
}
} else if (family === 'hcaptcha') {
fill('h-captcha-response', '.h-captcha');
fill('g-recaptcha-response', '.h-captcha');
if (window.hcaptcha) window.hcaptcha.getResponse = () => token;
callbacks('.h-captcha[data-callback]');
} else if (family === 'turnstile') {
const el = document.querySelector('.cf-turnstile');
fill((el && el.getAttribute('data-response-field-name')) || 'cf-turnstile-response', '.cf-turnstile');
if (window.turnstile) window.turnstile.getResponse = () => token;
callbacks('.cf-turnstile[data-callback]');
} else if (family === 'funcaptcha') {
for (const name of ['fc-token', 'verification-token']) if (document.querySelector('[name="' + name + '"]')) fill(name, 'body');
// the api.js script names a setup function (data-callback) that passes { onCompleted } to setConfig();
// call it again with a stand-in object to get onCompleted, then complete with the token
for (const s of document.querySelectorAll('script[data-callback]')) {
if (!/\/v2\/[0-9A-Fa-f-]{36}\/api\.js/.test(s.src)) continue;
let config = {};
const stub = new Proxy({}, { get: (_, k) => (k === 'setConfig' ? (c) => Object.assign(config, c) : () => {}) });
call(s.getAttribute('data-callback'), 'setup', stub);
call(config.onCompleted, 'onCompleted', { token });
}
}
return did;
};
export class CaptchaError extends Error {
constructor(code, taskId) {
super(`task ${taskId} failed: ${code}`); // failed tasks are not charged
this.code = code;
this.taskId = taskId;
}
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
// Solve one captcha with the v1 API and return task.solution ({ token, user_agent, ... }).
export async function solve(type, params, { timeoutMs = 180_000 } = {}) {
const key = process.env.NOPTCHA_KEY;
if (!key) throw new Error("set NOPTCHA_KEY to a nop_test_ or nop_live_ key, or to 'keyless' for the keyless sandbox");
const tasks = key === 'keyless' ? '/v1/sandbox/tasks' : '/v1/tasks';
const auth = key === 'keyless' ? {} : { Authorization: `Bearer ${key}` };
const deadline = Date.now() + timeoutMs;
// one idempotency key per task: a retry of the create request returns the same task instead of a second one
const idempotencyKey = crypto.randomUUID();
const call = async (method, path, init = {}) => {
for (let attempt = 0; ; attempt++) {
const res = await fetch(API + path, { method, ...init, headers: { ...auth, ...init.headers }, signal: AbortSignal.timeout(100_000) }).catch((err) => {
if (attempt >= 3) throw err;
return null; // network error: retry
});
if (res && res.status !== 409 && res.status !== 429 && res.status < 500) {
const body = await res.json();
if (!res.ok) throw new Error(`${res.status} ${body.code}: ${body.detail ?? body.title}`); // problem+json
return body;
}
if (res && attempt >= 3) throw new Error(`${res.status} ${(await res.json()).code}`);
await sleep(Math.min(Number(res?.headers.get('retry-after')) || 2 ** attempt, 30) * 1000);
}
};
let task = await call('POST', tasks, {
headers: { 'Content-Type': 'application/json', Prefer: 'wait=60', 'Idempotency-Key': idempotencyKey },
body: JSON.stringify({ type, params }),
});
while (task.status !== 'solved' && task.status !== 'failed') {
if (Date.now() > deadline) throw new Error(`task ${task.id} still ${task.status}`);
task = await call('GET', `${tasks}/${task.id}?wait=60`);
}
if (task.status === 'failed') throw new CaptchaError(task.error.code, task.id);
return task.solution;
}
// Find the first captcha on the page, solve it and put the token back. `evaluate(fn, arg)` runs fn in the page:
// pass your framework's (page.evaluate.bind(page) in Playwright, Puppeteer and Stagehand). Returns null when the
// page has no captcha this helper recognizes, else { type, params, solution, did }.
export async function solveOnPage(evaluate) {
const [captcha] = await evaluate(findCaptchas);
if (!captcha) return null;
const solution = await solve(captcha.type, captcha.params);
const did = await evaluate(putToken, { type: captcha.type, token: solution.token });
return { ...captcha, solution, did };
}

These helpers know the common ways sites embed each widget, not every one. If findCaptchas returns nothing on a page that clearly shows a captcha, read the parameters by hand (first table), call solve() with them, and pass the token to putToken.