reCAPTCHA with Vue.js example

Following base instructions from google site we can simply add next div:

<div class="g-recaptcha" :data-sitekey="rcapt_sig_key"></div>

Also define rcapt_sig_key in Vue data:

export default {
    data() {
      return {
        rcapt_sig_key: "YOUR KEY FROM GOOGLE",
        rcapt_id: 0 // will be used later
      }
    }
}

And also we need to load js in global <head>:

<script src='https://www.google.com/recaptcha/api.js'></script>

This already will work if you load your page directly (e.g. by typing/pasting url with a component on browser new tab, or press F5).

But, if you will be transitioned to the component you will have no captcha.

To solve this we can render captcha on mounted hook:

mounted() {
  if (window.grecaptcha) {
    this.rcapt_id = grecaptcha.render( $('.g-recaptcha')[0], { sitekey : this.rcapt_sig_key });
  }
},

This solves transition issue. It is very important here that we store current captcha ID in this.rcapt_id because captcha object can be changed if user will follow after capcha transition to another transition and then will return back. We will use this.rcapt_id when get response.

Then you can check that your captcha challenged by user (for UX):

g_recaptcha_response = grecaptcha.getResponse(this.rcapt_id);
if (g_recaptcha_response.length == 0) {
   this.error = "Compleate captcha challenge";
   return
}

And then send g_recaptcha_response to your backend to verify captcha.

Backend implementation example see here: https://maketips.net/tip/62/verify-recaptcha-in-drf

#recaptcha #vuejs
1
Ivan Borshchov profile picture
Nov 27, 2016
by Ivan Borshchov
Did it help you?
Yes !
No

Best related