How to bypass captcha using JavaScript

Learn how to automate captchas bypassing with JavaScript and NMPjs

In many cases captcha hinder accessibility, frustrate users, limits access to open information, makes testing application and sites difficult.

Article describes the procedure of bypassing captchas using the javascript captcha solver.

How to solve and bypass a captcha with JavaScript

This demo code is made to demonstrate how captcha solver API can be used to solve and bypass reCAPTCHA, but the code can also be used to bypass each other.

Create a function that will have 2 parameters:

  • The first parameter is the site key
  • The second parameter is the URL of the page containing the captcha challenge

Then we will make a GET request to the API endpoint 2captcha.com/in.php and provide values for these parameters:

  • key: Your API Key
  • method: Set the value to userrecaptcha
  • googlekey: The site key
  • pageurl: The URL of the page containing the captcha
  • json: Set the value to 1 so that the response will be in JSON form
function solveCaptcha(siteKey, pageUrl){
    //make printing text easier
    let log = (text) => {console.log(text)};
    let logErr = (text) => {console.error(text)};
    //your api key
    const apiKey = "YOUR_API_KEY";
    //make a GET request to 2captcha
    fetch(`https://2captcha.com/in.php?key=${apiKey}
    &method=userrecaptcha&googlekey=${siteKey}&pageurl=${pageUrl}&json=1`)
    .then(response => response.json())
    .then(data => {
        //do something with the data
    })
    .catch(error => {
        logErr('Error:', error);
    });
}

Aside from the catch block, we need to check, handle and print error(s) if an error should occur with our request.

On API page, you would see the list of possible errors and their description. Generally, all errors should have a status of 0.

function solveCaptcha(siteKey, pageUrl){
    const apiKey = "YOUR_API_KEY";
    //make a GET request to 2captcha
    fetch(`https://2captcha.com/in.php?key=${apiKey}
    &method=userrecaptcha&googlekey=${siteKey}&pageurl=${pageUrl}&json=1`)
    .then(response => response.json())
    .then(data => {
        //check if there's an error
        if(!data.status){
            //print out error
            logErr('Error:', (data.error_text !== undefined) ? data.error_text : data.request);
        }else{
            //do something else with the data
        }
    })
    .catch(error => {
        logErr('Error:', error);
    });
}

If the request is successful, an ID of the request will be returned and this will be used to keep track of the captcha, but if the request is not successful, an error will be returned and we need to make the function to be able to handle errors.

Now we need to make another call after 20 secs to the API endpoint 2captcha.com/res.php using the request ID and your API key to check the status of the captcha (if it has been solved).

I will use the setTimeout Function for this and we need to check and handle error(s) if an error should occur with our request.

function solveCaptcha(siteKey, pageUrl){
    const apiKey = "YOUR_API_KEY";
    //make a GET request to 2captcha
    fetch(`https://2captcha.com/in.php?key=${apiKey}
    &method=userrecaptcha&googlekey=${siteKey}&pageurl=${pageUrl}&json=1`)
    .then(response => response.json())
    .then(data => {
        //check if there's an error
        if(!data.status){
            //print out error
            logErr('Error:', (data.error_text !== undefined) ? data.error_text : data.request);
        }else{
            setTimeout(function(captchaId = data.request){
            //make another call with the ID to get the captcha's status
            fetch(`https://2captcha.com/res.php?key=${apiKey}&action=get&id=${captchaId}&json=1`)
                .then(response => response.json())
                .then(data => {
                    if(!data.status){
                        //print out error
                        logErr('Error:', (data.error_text !== undefined) ? data.error_text : data.request);
                    }else{
                        //do something else with the data
                    }
                })
                .catch(error => {
                    logErr('Error:', error);
                });
            }, 20000);
        }
    })
    .catch(error => {
        logErr('Error:', error);
    });
}

Now after 20 secs, the endpoint should return the solved captcha's token if the captcha has been solved or the endpoint will return the text CAPCHA_NOT_READY, if the captcha has not been solved.

We will use a conditional statement to check if the captcha has been solved or not.

  • If it has not been solved, we will use the setTimeout function to retry the request again after 5 secs.
  • If it has been solved, we will paste the token into a text field with the ID g-recaptcha-response.

We also need to handle any error(s) that might occur and print some texts for you to see the progress of the captcha solver function

function solveCaptcha(siteKey, pageUrl){
    //make printing text easier
    let log = (text) => {console.log(text)};
    let logErr = (text) => {console.error(text)};
    //your api key
    const apiKey = "YOUR_API_KEY";

    //make a GET request to 2captcha
    fetch(`https://2captcha.com/in.php?key=${apiKey}&method=userrecaptcha
    &googlekey=${siteKey}&pageurl=${pageUrl}&json=1`)
    .then(response => response.json())
    .then(data => {
        log('solving captcha...');
        //check if there's an error
        if(!data.status){
            //print out error
            logErr('Error:', (data.error_text !== undefined) ? 
                data.error_text : data.request);
        }else{
            log("Hurray! A worker has solved the captcha, we're retrieving the token...");
            log("Please wait while we retrieve the token...");
            setTimeout(function(captchaId = data.request){
                //make another call with the ID to get the captcha's status
                fetch(`https://2captcha.com/res.php?key=${apiKey}&action=get&id=${captchaId}&json=1`)
                .then(response => response.json())
                .then(data => {
                    if(!data.status && data.request != "CAPCHA_NOT_READY"){
                        //print out error
                        logErr('Error:', (data.error_text !== undefined) ? data.error_text : data.request);
                    }else if(!data.status && data.request == "CAPCHA_NOT_READY"){
                        log("Attempt to retrieve token failed, trying again in 5 secs...");
                        //repeat request after 5 secs
                        setTimeout(function(captchaId){
                            fetch(`https://2captcha.com/res.php?key=${apiKey}&action=get&id=${captchaId}&json=1`)
                            .then(response => response.json())
                            .then(data => {
                                //check if there's an error
                                if(!data.status){
                                    //print out error
                                    logErr('Error:', (data.error_text !== undefined) ? data.error_text : data.request);
                                }else{
                                    log("Captcha token has been retrieved");
                                    //output token
                                    document.querySelector('#g-recaptcha-response').innerHTML = data.request;
                                    log('captcha solved, you may submit the form');
                                }
                            })
                            .catch(error => {
                                logErr('Error:', error);
                            });
                        }, 5000); //end of step 3
                    }else{
                        log("Captcha token has been retrieved");
                        //output token
                        document.querySelector('#g-recaptcha-response').innerHTML = data.request;
                        log('captcha solved');
                    }
                })
                .catch(error => {
                    logErr('Error:', error);
                });
            }, 20000); //end of step 2
        }
    })
    .catch(error => {
        logErr('Error:', error);
    });//end of step 1
}

So when you want to bypass or solve a reCAPTCHA V2 on a webpage, invoke the function above in the console of the page, providing the required arguments, and wait for a response from the function.

//get url
const pageUrl = window.location.href;
//get sitekey
const siteKey = document.querySelector('[data-sitekey]').getAttribute('data-sitekey');
//invoke the solve captcha function
solveCaptcha(siteKey, pageUrl);

When you execute the function on a page with a captcha challenge, you will be notified of the progress until it has eventually solved the captcha.

How to solve and bypass a captcha with JavaScript using npm package @2captcha/captcha-solver

You can use our npm package @2captcha/captcha-solver to interact with the API.

Install the package using npm or yarn.
npm:
npm install @2captcha/captcha-solver

yarn:
yarn add @2captcha/captcha-solver

Create an instance:

import { Solver } from '@2captcha/captcha-solver'
const solver = new Solver(process.env.APIKEY)

Find the captcha parameters and send them to the appropriate method. In the code example below, a demonstration of sending Coordinates captcha:

const res = await solver.coordinates({
    body: img,
    textinstructions: 'Puzzle center | Центр пазла',
    imginstructions: instruction
})

After that, apply the received response according to how it is used on the page.

Final world

While this serves as an educational article, remember to prioritize ethical and responsible practices when utilizing Puppeteer.

References

Code examples

Support

We value feedback and want to make sure the service is perfect for your needs.