Was this helpful?
How captcha callback functions work
Technical engineer
Many modern websites use callback functions to pass captcha tokens into their business logic. If the callback isn't invoked—or is invoked incorrectly—the form may fail to submit, even if the captcha was solved correctly and the token is fully valid. Let's break down how callbacks work, explore typical scenarios, and cover reliable integration methods for automation scripts using 2Captcha.
What is a callback and why you need it
A callback is a JavaScript function that automatically executes after a captcha is successfully solved. It receives the solution token and performs site-specific actions: enabling the submit button, updating component state, triggering client-side validation, or initiating an asynchronous request to the server.
In manual workflows, the captcha widget invokes this function automatically. When automating via 2Captcha, however, the token is returned separately through the API, and your script must manually pass it to the callback so the site recognizes the verification as complete.
Why simply injecting the token into html isn't enough
Beginner developers often try to solve the problem by directly writing the token:
javascript
document.getElementById('g-recaptcha-response').value = token;
This approach only works on simple, static pages. In modern projects:
- Forms are managed via state managers that don't react to direct DOM modifications
- Validation libraries listen for input, change, or submit events
- The token may be validated exclusively inside the callback—not by reading the hidden field
- Protective mechanisms are added: execution context checks, timestamp validation, and form state verification
Without invoking the callback, the site often ignores the token or returns a verification error upon form submission.
How to find the callback function name on a page
-
data-callback attribute in the html widget:
html<div class="g-recaptcha" data-sitekey="..." data-callback="onCaptchaSuccess"></div> -
Initialization parameters in JavaScript:
javascriptgrecaptcha.render('widget-id', { callback: 'submitForm', sitekey: '...' }); -
DevTools → Elements: Search for data-callback, data-expired-callback attributes
-
DevTools → Sources / Network: Search keywords like callback, token, recaptcha, turnstile. Function names are often stored in the global window scope
-
Framework patterns: In React or Vue, callbacks may be passed via onSuccess props or custom events
If no function name is explicitly specified, the widget uses a built-in handler. In this case, it's usually sufficient to call the provider's standard method, retrieve the token from the hidden field, and manually trigger form submission.
How to manually invoke the callback after receiving a response from 2Captcha
Once you receive a token from 2Captcha, you need to pass it to the callback using browser automation.
Selenium (Python):
python
def invoke_callback(driver, callback_name, token):
exists = driver.execute_script(f"return typeof window.{callback_name} === 'function';")
if not exists:
raise ValueError(f"Callback {callback_name} not found in global scope")
driver.execute_script(f"window.{callback_name}(arguments[0]);", token)
Playwright (Python):
python
def invoke_callback_playwright(page, callback_name, token):
exists = page.evaluate(f"typeof window.{callback_name} === 'function'")
if not exists:
raise ValueError(f"Callback {callback_name} not found in global scope")
page.evaluate(f"window.{callback_name}('{token}')")
Fallback for sites without an explicit callback:
python
driver.execute_script("""
const el = document.getElementById('g-recaptcha-response');
el.value = arguments[0];
el.dispatchEvent(new Event('input', { bubbles: true }));
el.dispatchEvent(new Event('change', { bubbles: true }));
""", token)
Invisible captchas and spa frameworks: key considerations
Invisible captcha versions don't render a visible widget. Tokens are generated via programmatic calls:
javascript
grecaptcha.execute('sitekey', { action: 'submit' });
// or
turnstile.execute('sitekey');
After execution, the provider automatically triggers data-callback. In automation workflows, you'll need to wait for the token to appear in the hidden field, then manually invoke the callback.
Spa frameworks often wrap captchas in state-aware components. Direct DOM writes won't update internal state. Whenever possible, use the official callback if it's exported; otherwise, dispatch events with the correct types (input, change). If needed, emulate click/focus sequences to trigger built-in handlers.
Common pitfalls and how to avoid them
Issue: Callback invoked too early
Cause: Widget hasn't initialized yet; function doesn't exist on window.
Solution: Wait for scripts to load and for the data-callback attribute to appear before invoking.
Issue: Incorrect function name or scope
Cause: Function declared inside a module or closure.
Solution: Verify accessibility via typeof in DevTools. If inaccessible, fall back to simulating input/change events.
Issue: Expired token
Cause: 2Captcha tokens typically live for 1–2 minutes.
Solution: Invoke the callback immediately after receiving the ready status; avoid caching responses across sessions.
Issue: Ignoring data-expired-callback
Cause: Site updates UI when the token expires.
Solution: Implement retry logic to request a new captcha via 2Captcha and re-invoke the callback upon detecting expiration.
Checklist for reliable 2Captcha integration
- Identify the exact callback name via data-callback or source code analysis
- Confirm the function is accessible in the global window scope
- Wait for full widget initialization before injecting the token
- Pass the token immediately after receiving a response from 2Captcha—no delays
- If no explicit callback exists, simulate input and change events
- Handle token expiration scenarios and validation errors gracefully
- Log each invocation step for debugging and support ticket creation
Helpful resources
- Official 2Captcha API documentation: https://2captcha.com/2captcha-api
- Demo pages for integration testing: https://2captcha.com/demo
- Official repositories and code samples: https://github.com/2captcha
- Dashboard for task monitoring and balance management: https://2captcha.com/dashboard
Conclusion
The callback serves as the bridge between token generation and the site's business logic. Many projects rely on it specifically to unlock forms, trigger validation, and submit requests. When automating via 2Captcha, simply obtaining a token isn't enough: you must correctly pass it to the callback—or simulate the user interaction that would trigger it.
Following the proper sequence—waiting for initialization, validating the token, invoking the callback, and monitoring form submission—ensures stable script performance, even on complex spa sites with dynamically loaded captchas.