/find-recaptcha-params.js Secret
-
Star
(119)
You must be signed in to star a gist -
Fork
(41)
You must be signed in to fork a gist
-
-
Save 2captcha/2ee70fa1130e756e1693a5d4be4d8c70 to your computer and use it in GitHub Desktop.
| // IMPORTANT! PLEASE READ BEFORE USING THIS: | |
| // | |
| // 1. This is JavaScript. JavaScript is executed in a browser. | |
| // You can execute javascript when you control a browser with some browser automation tools. | |
| // To execute javascript from your code use the corresponding method provided by your tool, for example: | |
| // JavascriptExecutor interface in Selenium Java | |
| // ExecuteJavaScript method of WebDriver in Selenium for .Net | |
| // page.evaluate method in puppeteer | |
| // Please refer to docs of your favourite browser automation tool for more info | |
| // | |
| // 2. If you don't understand what UNDEFINED means in the javascript console, please read: | |
| // When you execute the code in the javascript console of your browser, the console evaluates EACH expression | |
| // and prints the returned value. And if your expression does not return any value (that is absolutely normal) | |
| // then you see 'undefined' in the console. This is NOT AND ERROR! | |
| // | |
| // For better understanding type the following in the console: | |
| // let myVar = 'foo' // defines myVar variable and sets it's value to 'foo' | |
| // You will see undefined in the console as this exression does not return anything. | |
| // | |
| // Then type the following | |
| // (() => 'bar')() // defines and calls a function that returns 'bar' | |
| // You will see "bar" as the function returns this value | |
| // | |
| // And one more case. Type: | |
| // ((a) => { b = a * 2 })(2) // defines and calls a function that does not return any value | |
| // What you will see? Yep, you will see undefined | |
| // | |
| // Hope now you understand some javascript console basics :) | |
| // | |
| // 3. The callback can be not the final step in your process. That is fine when after the callback you also need to perform | |
| // another action like button click, form submission, etc | |
| // | |
| // 4. NO, we can't make the same script for hCaptcha as the callback is not defined inside globaly accessible variables. | |
| // USAGE | |
| // paste the function definition into the console and then call the function: | |
| // | |
| // let res = findRecaptchaClients() | |
| // console.log(res) | |
| // | |
| // the function returns an array of objects with recaptcha parameters for each implementation found on the page | |
| function findRecaptchaClients() { | |
| // eslint-disable-next-line camelcase | |
| if (typeof (___grecaptcha_cfg) !== 'undefined') { | |
| // eslint-disable-next-line camelcase, no-undef | |
| return Object.entries(___grecaptcha_cfg.clients).map(([cid, client]) => { | |
| const data = { id: cid, version: cid >= 10000 ? 'V3' : 'V2' }; | |
| const objects = Object.entries(client).filter(([_, value]) => value && typeof value === 'object'); | |
| objects.forEach(([toplevelKey, toplevel]) => { | |
| const found = Object.entries(toplevel).find(([_, value]) => ( | |
| value && typeof value === 'object' && 'sitekey' in value && 'size' in value | |
| )); | |
| if (typeof toplevel === 'object' && toplevel instanceof HTMLElement && toplevel['tagName'] === 'DIV'){ | |
| data.pageurl = toplevel.baseURI; | |
| } | |
| if (found) { | |
| const [sublevelKey, sublevel] = found; | |
| data.sitekey = sublevel.sitekey; | |
| const callbackKey = data.version === 'V2' ? 'callback' : 'promise-callback'; | |
| const callback = sublevel[callbackKey]; | |
| if (!callback) { | |
| data.callback = null; | |
| data.function = null; | |
| } else { | |
| data.function = callback; | |
| const keys = [cid, toplevelKey, sublevelKey, callbackKey].map((key) => `['${key}']`).join(''); | |
| data.callback = `___grecaptcha_cfg.clients${keys}`; | |
| } | |
| } | |
| }); | |
| return data; | |
| }); | |
| } | |
| return []; | |
| } |
Hello everyone, I can't able to find the callback function for invisible recaptcha in Egypt e visa website . Can anyone help with that? I been stuck with this long days..
yes write me in https://www.upwork.com/freelancers/~01cee64871f1c9b633
I'm not able to message you there
Hello guys. Thank you for this useful conversation. Was anyone able to solve Instagram Recaptcha using this function. I'm struggling to :
1- get the sitekey which is hidden from the HTML that I get using Selenium
2- send back the response code to Instagram API
Here is what I get when I execute this function in the console :

Hello, webwonderer12. I have a question. I have a similar project with your posting.
But I can't run this script. If you can help me, please let me know.
Hello, everyone. Thanks for your consideration.
I have a project related to breaking recaptcha v2, but I have found news about Twocaptcha library.
def solve_captcha(login_url):
print('Solving the captcha (solve_captcha)')
api_key = ''
solver = TwoCaptcha(api_key)
html_string = driver.page_source
soup = BeautifulSoup(html_string, 'html.parser')
div_tag = soup.find('div', class_ = 'g-recaptcha')
site_key = div_tag['data-sitekey']
print(f'Site Key : {site_key}')
response = solver.solve_captcha(site_key, login_url)
print(f"Successfully solved the captcha. Captcha token: {response}")
return response
def submit_captcha(driver, code):
script = '''
function retrieveCallback(obj, visited = new Set()) {
if (typeof obj === 'function') return obj;
for (const key in obj) {
if (!visited.has(obj[key])) {
visited.add(obj[key]);
if (typeof obj[key] === 'object' || typeof obj[key] === 'function') {
const value = retrieveCallback(obj[key], visited);
if (value) {
return value;
}
}
visited.delete(obj[key]);
}
}
}
const callback = retrieveCallback(window.___grecaptcha_cfg.clients[0]);
if (typeof callback === 'function') {
callback('%s');
} else {
throw new Error('Callback function not found.');
}
''' % code
driver.execute_script(script)
This is modified code.
But here is a problem, I can't run submit_captcha function. I don't know the reason.
I hope anyone help me. Thanks again.
This solution works for me.
function getRecaptchaCallback() {
for (let item_key in ___grecaptcha_cfg.clients[0]) {
if (___grecaptcha_cfg.clients[0][item_key]) {
if (___grecaptcha_cfg.clients[0][item_key].hasOwnProperty(item_key)) {
if (___grecaptcha_cfg.clients[0][item_key][item_key].hasOwnProperty("callback")){
return ___grecaptcha_cfg.clients[0][item_key][item_key];
}
}
}
}
}
Hi guys any idea of finding hcaptcha callback?? I have been stuck for a week finding a solution
Hello guys!
I am trying to bypass a recaptcha, but there are two captchas. One is V2, and other one is V3.
here is the output of clients:
[{'callback': "___grecaptcha_cfg.clients['0']['C']['C']['callback']",
'function': 'buttonCaptchaSuccess',
'id': '0',
'pageurl': 'https://www.grammarly.com/signin',
'recaptchaPopupExists': False,
'sitekey': '6LcTmlolAAAAAKcDAZQE0o-1rBJT4R2xzuz6zqaA',
'version': 'V2'},
{'callback': "___grecaptcha_cfg.clients['100000']['C']['C']['promise-callback']",
'function': {},
'id': '100000',
'pageurl': 'https://www.grammarly.com/signin',
'recaptchaPopupExists': False,
'sitekey': '6LdSYv0UAAAAAF5PhF0Z1rK7QiupkyRBy1ebiFc4',
'version': 'V3'}]
So I tried that for V2, I tried to use buttonCaptchaSuccess function, but it gives me an error. I have this code:
page_source = browser.page_source
callback = vals[1]['callback']
buttonsuccess = vals[0]['function']
#solutionv3 = captcha_resolve(site_key='6LdSYv0UAAAAAF5PhF0Z1rK7QiupkyRBy1ebiFc4',url_p=browser.current_url)
#solutionv2= captcha_resolvev2(site_key='6LdSYv0UAAAAAF5PhF0Z1rK7QiupkyRBy1ebiFc4',url_p=browser.current_url)
if "human" in page_source and "g-recaptcha-response" in page_source:
print("yes")
#solution = captcha_resolve(site_key=vals[0]['sitekey'],url_p=vals[0]['pageurl'])
submitsj = f"""
let submitMyToken = (tokenV2,tokenV3) => {{
document.querySelector('#g-recaptcha-response').value = tokenV2
document.querySelector('#g-recaptcha-response-100000').value = tokenV3
{callback} (tokenV3)
{buttonsuccess}('tokenV2')
}}
submitMyToken('{solutionv2}','{solutionv3}')
"""
browser.execute_script(submitsj)
print("done!")
So to sum up I have tokens, I got them correctly. But I couldn't figure out how to send tokens correctly. Anyone help me?
function getRecaptchaCallback() {
for (let item_key in ___grecaptcha_cfg.clients[0]) {
if (___grecaptcha_cfg.clients[0][item_key]) {
if (___grecaptcha_cfg.clients[0][item_key].hasOwnProperty(item_key)) {
if (___grecaptcha_cfg.clients[0][item_key][item_key].hasOwnProperty("callback")){
return ___grecaptcha_cfg.clients[0][item_key][item_key];
}
}
}
}
}
Could you solve the problem of "not a function"?
Could you solve the problem of "not a function"?
Sorry, I didn't quite understand your question
wassup everyone i trying to solve capthca via seleinum python i got error ___grecaptcha_cfg is not a function and i tried to exeucte token via
document.getElementById("g-recaptcha-response").innerHTML="{token}"; not work also anyone have an idea to help me please
callback : "___grecaptcha_cfg.clients['0']['D']['D']['callback']"
function : "onCaptchaSuccess"
id : "0"
pageurl : "https://example.com"
sitekey : "6LcfWgIqAAAAAIMMEhI1qOognQxpDZ1aj80pvJdW"
Hi. I used the script and it work fine.
I found multiple callback with version V2 and V3, I must check they separately by multiple request to 2captcha?
I really need help to solve this enterprise captcha. Anyone have any ideas? I already tried
const frameReCaptcha = page
.frames()
.find((frame) => frame.url().includes('recaptcha/enterprise/anchor'))
// Gets key
const reCaptchaKey = jsonUtil.urlToObject(frameReCaptcha.url()).k
const captchaTaskObj = {
clientKey: 'mykey (omitted',
task: {
type: 'RecaptchaV2EnterpriseTaskProxyless',
websiteURL: 'https://www.rtdbrasil.org.br/',
websiteKey: reCaptchaKey,
// "enterprisePayload": {
// "s": "SOME_ADDITIONAL_TOKEN"
// }
},
}
console.log(captchaTaskObj, 'console log of captchaTaskObj')
Somebody help me out please, I'm trying to bypass this login page: PAGE
This is the response from the findRecaptchaClients():
[{
"id": "100000",
"version": "V3",
"sitekey": "6Lc3aVcbAAAAAPt5jshxqfNB6unyIX6s-eGR3hq5",
"callback": null,
"function": null,
"pageurl": "https://loopcommunity.com/user/login"
}]The captcha solves "fine" according to 2captcha, but when setting that captcha response and using it in the request I get an invalid captcha response from the API :(
Anybody have any idea of what I could be missing?
Somebody help me out please, I'm trying to bypass this login page: PAGE This is the response from the findRecaptchaClients():
[{ "id": "100000", "version": "V3", "sitekey": "6Lc3aVcbAAAAAPt5jshxqfNB6unyIX6s-eGR3hq5", "callback": null, "function": null, "pageurl": "https://loopcommunity.com/user/login" }]The captcha solves "fine" according to 2captcha, but when setting that captcha response and using it in the request I get an invalid captcha response from the API :(
Anybody have any idea of what I could be missing?
I am facing the same problem as @svillacreses. The website is https://portel-pa.desenvolvecidade.com.br/desenvolvecidade/#/login. Someone has found something about it?
Hey, sorry if my question is very childish. I don't know much about the ReCaptcha and want to solve Recaptcha v3. I'm receiving the token from 2captcha API but when I submit it. It doesn't work. Where should I look?
What might be the issue?
I'm submitting using the requests not in a browser automation etc. Would you like me to know the callback function to make it work even in the requests?
Привет, извините, если мой вопрос совсем детский. Я не очень разбираюсь в ReCaptcha и хочу решить Recaptcha v3. Я получаю токен от API 2captcha, но когда я его отправляю. Он не работает. Где мне искать? В чем может быть проблема? Я отправляю с помощью запросов, а не в автоматизации браузера и т. д. Хотите, чтобы я узнал функцию обратного вызова, чтобы она работала даже в запросах?
Пишите в поддержку вам ответят
Hello, I'm trying to validate an invisible Recaptcha v2, although it's returning the token and I'm sending it to the recaptcha, it's not working:
I have the payload to create the task:
payload = {
"clientKey": api_key,
"task": {
"type": "RecaptchaV2TaskProxyless",
"websiteURL": url,
"websiteKey": site_key,
"isInvisible": True,
}
}
After creating it I return the task id and do a get to get the resolved token and here I am passing it to the recpatcha:
try:
textarea = driver.find_element(By.CSS_SELECTOR, "textarea[name='g-recaptcha-response']")
print("Elemento textarea encontrado:", textarea)
except Exception as e:
raise Exception(f"No se pudo encontrar el textarea del reCAPTCHA: {e}")
# Inyectar el token directamente en el textarea
try:
driver.execute_script(
f"arguments[0].value = '{token}'; arguments[0].dispatchEvent(new Event('input', {{ bubbles: true }}));", textarea
)
print("Token de reCAPTCHA inyectado.")
# driver.execute_script(
# f"document.getElementById('g-recaptcha-response-100000').innerHTML='{token}';"
# )
injected_value = textarea.get_attribute("value")
print(f"Valor del textarea después de la inyección: {injected_value}")
# driver.execute_script("grecaptcha.execute();")
sleep(2)
driver.execute_script("document.getElementById('btnValidar').click();")
# driver.getElementById("btnValidar").submit()
# driver.find_element(By.CSS_SELECTOR, btn_enviar_form).click()
print("Click botón enviar data - form")
log_message("Click botón enviar data - form", log_file)
except Exception as e:
raise Exception(f"No se pudo inyectar el token en el textarea: {e}")
After injecting the token, I send the form but it is not sending it because an alert appears that says "The captcha cannot be validated."
Hi guys, how are you? I can't get past this captcha at all: https://www.freepik.com/log-in?client_id=freepik&lang=en
After clicking on log in, the invisible captcha v2 appears. I went to support and they told me there was a v3 behind it, but this is really strange! Can anyone help me?
嗨,我正在尝试绕过 google/sorry/index 页面。并遵循相同的方法,这是代码 def Submit_captcha(driver, code): script = '''
let x = (token) => { document.querySelector('#g-recaptcha-response').value = token ___grecaptcha_cfg.clients['0']['B']['B']['callback'] (token) } x('%s') ''' % (code,) driver.execute_script(script)我收到的错误是 selenium.common.exceptions.JavascriptException: Message: javascript error: ___grecaptcha_cfg.clients.0.BBcallback 不是函数。
'___grecaptcha_cfg.clients['0']['B']['B']['callback']' 它是一个回调函数的字符串,所以我尝试使用令牌调用该回调函数,但它重新加载页面并再次出现 recaptcha(并且在 url 中删除了所有查询参数)....
谁能帮我这个??
I have the same problem and I'm looking for an answer
你解决了吗
Hi, You may need to enter the captcha frame and call the function from there.
Has anyone solved the problem that callback is empty?
I still encountered it today, and I am sure that the words data-callback do not exist in the page.
I read the execute method to try to find the callback function, but it seems a bit too troublesome to do it alone.
my target page is https://www.pokemoncenter-online.com/login/
Documenting HOWTO as it wasn't originally clear to me what to do with the code - which helps you get the callback function from a reCAPTCHA page that uses one (i.e., a callback function)
1/ Go to the page containing the reCAPTCHA in a browser window
2/ Open "Developer Tools" and switch to the Console tab
3/ Copy (all of the lines of the function - 46 to 83) function findRecaptchaClients() from the find-recaptcha-params-js and paste it into the prompt in the Console tab and press ENTER
4/ Paste findRecaptchaClients() into the Console prompt and press ENTER - this executes the function against the page
5/ Expand "0" (json) object in the result and you will see the callback function details e.g., in this example, it is named "handleCaptchaToken"

6/ In my Selenium/Python code - using the information above, below is how I integrate it into submit process ...
driver.execute_script(f'handleCaptchaToken("{code}")')
driver.execute_script(f"___grecaptcha_cfg.clients['0']['V']['V']['callback']")
try:
submit_btn = driver.find_element(By.CSS_SELECTOR, 'button[type="submit"]')
submit_btn.click()
print("submitted")
except:
print("didnt submit")
@SekiyoKana @handlerMan If you haven’t solved this yet, you can contact me via TG. I can help you. My TG ID is https://t.me/eCyberNinja.
Hi All, I am able to solve the reCAPTCHA in my Selenium/Python3 script, and insert the code into g-recaptcha-response.
For the callback, the following is the code snippet ({code} contains the response code):
driver.execute_script(f'("{code}")')
driver.execute_script(f"___grecaptcha_cfg.clients['0']['V']['V']['callback']")
It is not complaining (no errors) but it is not working either i.e., the "ENTER" button on the page remains grayed out. Any ideas?

So someone said that from this screenshot, the website is using "JavaScript dynamic callbacks". Please how do I handle that since the standard method (my previous comment) doesn't work? Thanks
Hi, for some reason, I can't solve the captcha after using this script. Can you tell me why? And when should I insert it? Before or after the captcha appears (as a pop-up window).
Thank you for your response
let x = (token) => {{ ___grecaptcha_cfg.clients[0].G.G.callback(token); document.querySelector('#g-recaptcha-response').innerText = token; }} x('{code}')





hcaptcha also has a callback, How to solve it