简体   繁体   中英

Enable button on callback if recaptcha successful (Google recaptcha v2)

I have a simple page that has a button with a link variable linked to it, I want to add a recaptcha validation to the page, in a way where the button will be only visible if the recaptcha is validated

 <a id="cl-link" class="cl-link-button" href="<?php echo esc_url($url); ?>" rel="nofollow"><span></span></a>

Full code:

 <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo('charset'); ?>" /> <meta name="robots" content="noindex"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src='https://www.google.com/recaptcha/api.js'></script> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"> <link rel='stylesheet' id='link-single' href='<?php echo DOO_URI,'/css/cl.css'; ?>' type='text/css' media='all' /> </head> <body> <a id="cl-link" class="cl-link-button" href="<?php echo esc_url($url); ?>" rel="nofollow"><span></span></a> </body> </html>

If you use Javascript to render the Recaptcha component, a function is fired after Recaptcha has been successfully verified.

So, for Recaptcha v3:

<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
  grecaptcha.ready(function() {
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
         $("#cl-link").show();
      });
  });
</script>

Or, if you are using Recaptcha v2 and html, there is an attribute data-callback to add a callback function to the component.

<div class="g-recaptcha" data-callback="recaptcha_callback" data-sitekey="xxxxx"></div>  

In your Javascript:

<script type="text/javascript">
    function recaptcha_callback(){
      $('#cl-link').show();
    }
</script>

I have assumed that you have JQuery in your web page for displaying the button. If not, you should use native Javascript to show the button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM