How to click on reCAPTCHA with Codeception


When writing our PHP Selenium WebDriver tests, how can we click on the reCAPTCHA checkbox with Codeception?

The module has the method switchToIFrame, which takes the iframe name as the first argument.

However, we have a problem—the reCAPTCHA iframe name is a randomly generated hash (see example below):

<iframe
  src="https://www.google.com/recaptcha/api2/anchor?ar=1&k=6Le-wvkSAAAAAPBMRTvw0Q4Muexq9bi0DJwx_mJ-&co=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbTo0NDM.&hl=en&v=v1557729121476&size=normal&cb=9iioc4rv76zy"
  width="304"
  height="78"
  role="presentation"
  name="a-urpst7czwgqi"
  frameborder="0"
  scrolling="no"
  sandbox="allow-forms allow-popups allow-same-origin allow-scripts allow-top-navigation allow-modals allow-popups-to-escape-sandbox"
></iframe>

Thus, to retrieve the iframe name, we can use JavaScript:

document.querySelector("iframe[src*='recaptcha']").getAttribute("name");

To execute the script and get the value in our test, you can use executeJS:

$name = $I->executeJS(
  'return document.querySelector("iframe[src*=\'recaptcha\']").getAttribute("name");'
);

Now, you can switch to the iframe, click on the reCAPTCHA anchor button, and switch back to the main window:

$I->switchToIFrame($name);
$I->click('#recaptcha-anchor');
$I->switchToIFrame();

Alternatively, you can override the reCAPTCHA iframe with a custom name:

$name = 'my-recaptcha';
$I->executeJS(
  sprintf(
    'document.querySelector("iframe[src*=\'recaptcha\']").setAttribute("name", "%s");',
    $name
  )
);


Please support this site and join our Discord!