Skip to content

Instantly share code, notes, and snippets.

@2captcha
Last active July 27, 2024 14:56
Show Gist options
  • Save 2captcha/2ee70fa1130e756e1693a5d4be4d8c70 to your computer and use it in GitHub Desktop.
Save 2captcha/2ee70fa1130e756e1693a5d4be4d8c70 to your computer and use it in GitHub Desktop.
A piece of javascript code that can help you to find reCAPTCHA parameters
// 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 [];
}
@526319491
Copy link

hcaptcha also has a callback, How to solve it

@Hochmah
Copy link

Hochmah commented Feb 19, 2024

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

@GGGasd123
Copy link

if there si 2 ID ,so how can i solve it?
like this
array("0"=array("callback"="___grecaptcha_cfg.clients['0']['N']['N']['callback']","function"=array(),"id"="0","pageurl"="page","sitekey"="6LcbjYEpAAAAACC2jS-upwEdTo5OUj6b9amiGyGt","version"="V2"),"1"=array("callback"="___grecaptcha_cfg.clients['1']['N']['N']['callback']","function"=array(),"id"="1","pageurl"="page","sitekey"="6LcbjYEpAAAAACC2jS-upwEdTo5OUj6b9amiGyGt","version"="V2"),"data"=null)

@Altimis
Copy link

Altimis commented Mar 9, 2024

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 :
gto

@hi-tech-AI
Copy link

hi-tech-AI commented Mar 10, 2024

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.

@hi-tech-AI
Copy link

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.

@progeroffline
Copy link

progeroffline commented Mar 27, 2024

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];
        }
      }
    }
  }
}

@sakibovi123
Copy link

Hi guys any idea of finding hcaptcha callback?? I have been stuck for a week finding a solution

Url: https://www.bakecaincontrii.com/u/login/

@maligul
Copy link

maligul commented May 2, 2024

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?

@emarcari
Copy link

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"?

@progeroffline
Copy link

progeroffline commented May 23, 2024

Could you solve the problem of "not a function"?

Sorry, I didn't quite understand your question

@0dcj
Copy link

0dcj commented Jul 3, 2024

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"

@alexsavenko
Copy link

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?

@igorovisk
Copy link

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')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment