Skip to content

Instantly share code, notes, and snippets.

@2captcha
Last active May 2, 2024 05:54
Show Gist options
  • Star 97 You must be signed in to star a gist
  • Fork 33 You must be signed in to fork a gist
  • 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 [];
}
@SOOBINIM
Copy link

SOOBINIM commented May 8, 2023

The website in question is using reCAPTCHA V2 Invisible. As there is no separate submit button, I tried to use a callback function, but even after using the findRecaptchaClients function, I cannot find the value behind ___grecaptcha_cfg.clients. How can I solve the captcha on this website?

target site : https://www.weebly.com/editor/apps/showCommentForm-v2.php?user_id=56503399&blog_id=354154946405093163&post_id=241954732946847502

@anovob
Copy link

anovob commented May 8, 2023 via email

@vitalisc
Copy link

vitalisc commented May 8, 2023

why message you on telegram when you can reply here , sounds fishy to me

@anovob
Copy link

anovob commented May 8, 2023 via email

@bosasj
Copy link

bosasj commented May 31, 2023

Gosh i really need help. Trying to beat the recaptchas on these 3 sites. I can get each to work with 2captcha (C#) but I dont know what to do with the key response. Can someone help?
National Sex Offender Registry: https://www.nsopw.gov/

TN Felony Offender Registry: https://foil.app.tn.gov/foil/search.jsp

Interstate Compact Offender Tracking System (ICOTS), formerly TN Out of State Probation & Parole Registry: https://pwp.interstatecompact.org/PWP/searches
The sire with images i havent automated the downloading of image yet either (need help with that)

Im using C#.net 6 with puppeteer and am having IMMENSE trouble automating all of this so that puppeteer can bypass the captcha


using PuppeteerExtraSharp.Plugins.ExtraStealth;
using PuppeteerExtraSharp;
using PuppeteerSharp;
using TwoCaptcha.Captcha;
using PuppeteerExtraSharp.Plugins.Recaptcha.Provider.AntiCaptcha;
using PuppeteerExtraSharp.Plugins.Recaptcha;
using RestSharp;
using PuppeteerExtraSharp.Plugins.AnonymizeUa;



//var solver = new TwoCaptcha.TwoCaptcha("key");
//// TEXT RECAPTCHA - works on this site
//ReCaptcha captcha = new ReCaptcha();
//captcha.SetSiteKey("6Lfe-CIUAAAAAK8e84ph-swGwmSmjHyKroAkmBc2");
//captcha.SetUrl("https://pwp.interstatecompact.org/PWP/searches/");
//captcha.SetVersion("v2");
//captcha.SetEnterprise(false);
//captcha.SetDomain("google.com");
//captcha.SetAction("verify");
//captcha.SetScore(0.3);

//try
//{
//    solver.Solve(captcha).Wait();
//    Console.WriteLine("Captcha solved: " + captcha.Code);
//}
//catch (AggregateException e)
//{
//    Console.WriteLine("Error occurred: " + e.InnerExceptions.First().Message);
//}


//// TEXT RECAPTCHA - works on this site
//ReCaptcha captcha = new ReCaptcha();
//captcha.SetSiteKey("6LfZO6EaAAAAALrsTdskSwocDAxq7P7Cu_ZgXun_");
//captcha.SetUrl("https://www.nsopw.gov/en/Search/Verification");
//captcha.SetVersion("v2");
//captcha.SetEnterprise(false);
//captcha.SetDomain("google.com");
//captcha.SetAction("verify");
//captcha.SetScore(0.3);

//try
//{
//    solver.Solve(captcha).Wait();
//    Console.WriteLine("Captcha solved: " + captcha.Code);
//}
//catch (AggregateException e)
//{
//    Console.WriteLine("Error occurred: " + e.InnerExceptions.First().Message);
//}


// TEXT IMG CAPTCHA  - just a test against the API using a manually saved recaptcha image with text

//Normal captcha = new Normal();
//captcha.SetFile("C:\\deleteme\\text.jpg");
//captcha.SetNumeric(4);
//captcha.SetMinLen(4);
//captcha.SetMaxLen(20);
//captcha.SetPhrase(true);
//captcha.SetCaseSensitive(true);
//captcha.SetCalc(false);
//captcha.SetLang("en");
//captcha.SetLang("en");

//try
//{
//    solver.Solve(captcha).Wait();
//    Console.WriteLine("Captcha solved: " + captcha.Code);
//}
//catch (AggregateException e)
//{
//    Console.WriteLine("Error occurred: " + e.InnerExceptions.First().Message);
//}

@AstFreelancer
Copy link

Well, I try to parse a captcha in https://visa.vfsglobal.com/rus/en/fra/login and this JS code gets me this:
___grecaptcha_cfg.clients['0']['l']['l']['callback']
Then in my Python code I write:
driver.execute_script(("window.___grecaptcha_cfg.clients[0].l.l.callback('{}')".format(code)))
And I get "Mandatory field cannot be left blank" error.

@anovob
Copy link

anovob commented Aug 8, 2023

Well, I try to parse a captcha in https://visa.vfsglobal.com/rus/en/fra/login and this JS code gets me this: ___grecaptcha_cfg.clients['0']['l']['l']['callback'] Then in my Python code I write: driver.execute_script(("window.___grecaptcha_cfg.clients[0].l.l.callback('{}')".format(code))) And I get "Mandatory field cannot be left blank" error.

It's easy check my previous reply

@AstFreelancer
Copy link

There is no answer in it.

@Bzyk0945
Copy link

Bzyk0945 commented Aug 8, 2023

Hello, from the function above I received this information:

___grecaptcha_cfg.clients['0']['l']['l']['callback']
function: "recaptchaCallback"
version: "V2"

And the extension to chrome 2captcha solver, throws an error: ERROR_CAPTCHA_UNSOLVABLE
looking at their site I get information that captcha v2 is not v2 at all but v3, does anyone know how to solve this? I would like to do it in node js

{
  "googlekey": "6Le0FWYUAAAAAFQnuKzk0v9smHMBkfxt9Q7NHbW1",
  "pageurl": "https://www.margonem.pl/intro/",
  "proxytype": "HTTP",
  "version": "v3",
  "action": "",
  "min_score": 0.9,
  "invisible": 0,
  "domain": "",
  "recaptcha_discount": 0,
  "captchatype": "recaptcha_v3",
  "stoken": "",
  "proxy": "",
  "soft_id": 2834
}

@iprahka
Copy link

iprahka commented Aug 11, 2023

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)

Try this, It helped me. I was facing the same issue 10 mins ago. I put this code right after I got the solved captcha token. Im working with vfsglobal too, so I believe it can help you

@AstFreelancer
Copy link

@iprahka Thank you. I managed to find the callback with the code above, but seems there are a combination of V2 and V3 captchas so I cannot solve this task in any case. If you have the working code for VFS, could you please share it with me?

@HhvrshH
Copy link

HhvrshH commented Oct 1, 2023

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)

Try this, It helped me. I was facing the same issue 10 mins ago. I put this code right after I got the solved captcha token. Im working with vfsglobal too, so I believe it can help you

where i must paste the token previous run this code?

@codeblue12
Copy link

https://gmx.com sitekey = '6LdAZJIbAAAAAAhRV4Ojgba7ggroit4oKK6gYyZX' callback = ___grecaptcha_cfg.clients[0].J.J.callback
Now How can I submit callback???????

driver.execute_script("window.___grecaptcha_cfg.clients[0].C.C.callback('{}')".format(TOKEN))

what is this .format(TOKEN) is there anything to replace with the TOKEN?

@iprahka
Copy link

iprahka commented Oct 4, 2023

code

Sorry, I didnt send the whole code. You should enter that into the end of that script instead of 'code' word
Take a look how it works with me:

def solve_captcha(login_page_url):
    print('Solving the captcha (solve_captcha)')
    config = {
        'server':           'rucaptcha.com',
        'apiKey':           '55555556666667ad3c011111111111111111a18ca722222111111111e',
    }
    solver = TwoCaptcha(**config)
    response = solver.recaptcha(sitekey='1111111LfDUY2222bAAAAAPU5MWGT_w0x5M-8RdzC29SClOfI', url=login_page_url)
    code = response['code']
    print(f"Successfully solved the captcha. Captcha token: {code}")
    return code


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)

And here's how I call these functions:

captcha_code = solve_captcha(login_page_url)
submit_captcha(driver, captcha_code)

@codeblue12
Copy link

rucaptcha.com

rucaptcha.com? is it recaptcha's server

@iprahka
Copy link

iprahka commented Oct 4, 2023

rucaptcha.com

rucaptcha.com? is it recaptcha's server

Yeah. It’s the same

@webwonderer12
Copy link

code

Sorry, I didnt send the whole code. You should enter that into the end of that script instead of 'code' word Take a look how it works with me:

def solve_captcha(login_page_url):
    print('Solving the captcha (solve_captcha)')
    config = {
        'server':           'rucaptcha.com',
        'apiKey':           '55555556666667ad3c011111111111111111a18ca722222111111111e',
    }
    solver = TwoCaptcha(**config)
    response = solver.recaptcha(sitekey='1111111LfDUY2222bAAAAAPU5MWGT_w0x5M-8RdzC29SClOfI', url=login_page_url)
    code = response['code']
    print(f"Successfully solved the captcha. Captcha token: {code}")
    return code


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)

And here's how I call these functions:

captcha_code = solve_captcha(login_page_url)
submit_captcha(driver, captcha_code)

Thank you for providing this code—it successfully met my requirements. However, I have a query. We are employing JavaScript within Python. If another instance of JavaScript is present in the browser using the same callback function, could there be a collision? Additionally, what are the chances of detecting that we are utilizing an API to address the captcha? Can someone provide insights on this matter?

@JFurqu1m
Copy link

JFurqu1m commented Nov 7, 2023

Hello everyone, I'm trying to break the captcha on this site, but I can't do it, could you help me?

https://portal.ifood.com.br/login

@maksimrudn
Copy link

How to find recaptcha callback.
findRecaptchaFunction() shows one client with null callback.
What to do next?

image

@prachib-vision
Copy link

prachib-vision commented Dec 7, 2023

hii, i am trying to bypass google/sorry/index page. and follow the same method, and this is the code
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)

here error i am getting is that selenium.common.exceptions.JavascriptException: Message: javascript error: ___grecaptcha_cfg.clients.0.B.B.callback is not a function.

'___grecaptcha_cfg.clients['0']['B']['B']['callback']' it is a string that is callback funcion, so i tried to call that callback function with token but it reload the page and again recaptcha appear with (and all queryparam removed in url)....

can anyone help me with this??

@zqq-nuli
Copy link

zqq-nuli commented Jan 1, 2024

嗨,我正在尝试绕过 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

@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

@morning120429
Copy link

morning120429 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.

@morning120429
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?

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