Giter Site home page Giter Site logo

vue-recaptcha-v3's Introduction

Vue reCAPTCHA-v3

npm npm type definitions

A simple and easy to use reCAPTCHA (v3 only) library for Vue based on reCAPTCHA-v3.

The latest version of this package supports Vue 3! See here for Vue 2 usage.

Install

With NPM:

$ npm install vue-recaptcha-v3

With Yarn:

$ yarn add vue-recaptcha-v3

Prerequisites

To use this package you only need a valid site key for your domain, which you can easily get here.

Usage

import Vue from 'vue'
import { VueReCaptcha } from 'vue-recaptcha-v3'

// For more options see below
Vue.use(VueReCaptcha, { siteKey: '<site key>' })

new Vue({
  methods: {
    async recaptcha() {
      // (optional) Wait until recaptcha has been loaded.
      await this.$recaptchaLoaded()

      // Execute reCAPTCHA with action "login".
      const token = await this.$recaptcha('login')

      // Do stuff with the received token.
    }
  },
  template: '<button @click="recaptcha">Execute recaptcha</button>'
})

Vue 3 Composition

import { createApp } from 'vue'
import { VueReCaptcha, useReCaptcha } from 'vue-recaptcha-v3'

const component = {
  setup() {
    const { executeRecaptcha, recaptchaLoaded } = useReCaptcha()

    const recaptcha = async () => {
      // (optional) Wait until recaptcha has been loaded.
      await recaptchaLoaded()

      // Execute reCAPTCHA with action "login".
      const token = await executeRecaptcha('login')

      // Do stuff with the received token.
    }

    return {
      recaptcha
    }
  },
  template: '<button @click="recaptcha">Execute recaptcha</button>'
}

createApp(component)
  .use(VueReCaptcha, { siteKey: '<site key>' })

TypeScript + Vue 3

To get type suggestions for instance variables (this is not needed for composition API), create a new file called shims-vue-recaptcha-v3.d.ts and put the following inside it:

import { ReCaptchaInstance } from 'recaptcha-v3'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $recaptcha: (action: string) => Promise<string>
    $recaptchaLoaded: () => Promise<boolean>
    $recaptchaInstance: ReCaptchaInstance
  }
}

Options

This plugin offers optional options to configure the behavior of some parts.

Available options:

Name Description Type Default value
siteKey The site key for your domain from Google. string none
loaderOptions Optional options for the recaptcha-v3 loader. The available options are described here. object null

Usage

To use the options just pass an object to the Vue.use(...) method. For example:

import Vue from 'vue'
import { VueReCaptcha } from 'vue-recaptcha-v3'

Vue.use(VueReCaptcha, {
  siteKey: '<site key>',
  loaderOptions: {
    useRecaptchaNet: true
  }
})

Advanced usage

Some topics which are not commonly used, but required in some cases.

Access reCAPTCHA-v3 instance

In some cases it's necessary to interact with the reCAPTCHA-v3 instance, which provides more control over reCAPTCHA.

const recaptcha = this.$recaptchaInstance

// Hide reCAPTCHA badge:
recaptcha.hideBadge()

// Show reCAPTCHA badge:
recaptcha.showBadge()

vue-recaptcha-v3's People

Contributors

aklinker1 avatar dependabot-preview[bot] avatar dependabot[bot] avatar depfu[bot] avatar dispatchcommit avatar gerrywilko avatar wipeair avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

vue-recaptcha-v3's Issues

show captcha on specific pages

Hello
After adding component like
Vue.use(VueReCaptcha, { siteKey: "....." })

captcha
image
appear on every page of application

For now I hide in with CSS but
it would be nice to have option show it on selected pages (components)

Adding container creates reCAPTCHA ERROR: Invalid domain for site key

Adding container creates reCAPTCHA ERROR: Invalid domain for site key

Here is an excerpt of my code

.use(VueReCaptcha, {
    siteKey: '<my-real-key>',
    loaderOptions: {
    explicitRenderParameters: {
        container: 'reCaptcha',
        badge: 'inline',
    },
},

The badge is rendered inside the <div class="reCaptcha"></div> with an error message: reCAPTCHA ERROR: Invalid domain for site key and then the code fails. If i remove container: 'reCaptcha', from the code it works (set aside the location for the badge).

Anyone have a solution for this?

Can you provide a better example?

I'm trying to use this with quasar, but I can get the component render, is only rendering a plain button, but don't nothing. The demo use ts, but I'm using js.

Can i Add this to a login buton?

hi i just wanna ask can i use recaptcha in vue project that uses vuetify?,
and i want to connect the recapcha into login button, thanks

Unexpected token { (Nuxt)

Using Nuxt, when I try to load the library in the way shown in the examples, I get an Unexpected token { syntax error. My guess from looking at the bundled/compiled code in the package, is that for reason some the ES6 import/export statements are causing it, but I'm not sure.

Recaptcha doesn't catch spam

Hi. I installed recaptcha v3 into my login form - but i think recaprtcha doesn't catch spam. I send a lot of requests but recaptcha doesn't show me modal with images(gidranst or bus and ect.) for check on robot . It's normal behavior?
Because recaptcha v2 shows modal with images after 5-7 attempts

Typo in README

Just saw a tiny typo in the README.md which caused me some errors after a copy paste.
Instead of "useRecaptcha" it is "useReCaptcha" with a capital C.
I'm pointing to the function used for the Vue 3 composition api.

not work in mobile browser

Hi bro! i have tested recatcha it work really good but in mobile it cant work
can u check and fix it?

useReCaptcha composable returns undefined

Hi, i'm developing a website with Quasar framework v2 (based on vue 3).
I've created a dedicated bootfile in order to add the plugin to the project.

import { boot } from 'quasar/wrappers';
import { VueReCaptcha } from 'vue-recaptcha-v3';

export default boot(({ app }) => {
  app.use(VueReCaptcha, {
    siteKey: 'my-key-***********',
  });
});

Then inside my composable i added a button and called the composable inside the setup.
When clicking the button the console will log the result of the composable which is undefined.

Also wen the page loads this warning will appear:

[Vue warn]: injection "Symbol(VueReCaptchaInjectKey)" not found. 
  at <RegistrationPage onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <QPageContainer> 
  at <QLayout view="lHh Lpr lFf" > 
  at <MainLayout onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< undefined > > 
  at <RouterView> 
  at <App>

Any ideas on what could be the problem here?
Thanks! :)

Cannot detect if recaptcha failed to load

Hi, I noticed in the you are catching the error when recaptcha fails to load:

https://github.com/AurityLab/vue-recaptcha-v3/blob/master/src/ReCaptchaVuePlugin.ts#L28

However this just causes await this.$recaptchaLoaded(); to endlessly await in the event that recaptcha fails to load (e.g. region blocking or user's browser blocks the request). This means I cannot rely on await this.$recaptchaLoaded(); to check if the plugin has loaded because I cannot tell if I should just be waiting for the plugin to load, or if there is an issue.

Ideally this.$recaptchaLoaded(); should reject in the event of an error, so that I can try...catch... it and handle the error myself.

TypeError: _this.$recaptcha is not a function

Get this error when I try to use the package in my Vue app. Package is imported in my main app.js file and in the component. Using code copied from the examples. No idea how to fix.

Timeout error

Hello. In my app i make several async uploads simultaneously and try to get a unique token for each of them. The problem is that i get a timeout error in most cases. I just wanted to ask, if this is a normal behavior and we can only have one token at the same time, or this is a throttle from google's servers, or this is a bug. Thank you.

Feature request: Actions

Actions

  • reCAPTCHA v3 introduces a new concept: actions.

reCAPTCHA you enable two new features:

a detailed break-down of data for your top ten actions in the admin console
adaptive risk analysis based on the context of the action (abusive behavior can vary)
Importantly, when you verify the reCAPTCHA response you should also verify that the action name matches the one you expect.

  grecaptcha.ready(function() {
      grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'});
  });
  • this feature is missing in your current implementation.

SSR: No reCAPTCHA clients exist

Hi,

I'm doing server side rendering, and while developing (serving) I succeed in making this plugin working. But as soon as I build my project and run the server, from my client I get this issue:

Error: No reCAPTCHA clients exist.
    at tV (recaptcha__en_gb.js:488)
    at Object.Bt [as execute] (recaptcha__en_gb.js:502)
    at ReCaptchaInstance.js:12
    at new Promise (<anonymous>)
    at ReCaptchaInstance../node_modules/recaptcha-v3/dist/ReCaptchaInstance.js.ReCaptchaInstance.execute (ReCaptchaInstance.js:11)
    at VueComponent.Vue.$recaptcha (ReCaptchaVuePlugin.js:52)
    at VueComponent._callee$ (LandingMain.vue?81ec:42)
    at tryCatch (runtime.js:65)
    at Generator.invoke [as _invoke] (runtime.js:303)
    at Generator.prototype.<computed> [as next] (runtime.js:117)

I'm using the $recaptcha(XXX) function a few seconds after the website has been loaded. I don't understand where this comes from 😢

Note that I tried to move my Vue.use(VueRecaptcha) at different places in my code (client entry, after app created...).

Does someone has succeeded in making it working with basic SSR from Vue?

Thank you,

useRecaptcha() causes error in Vue 3

I always received following error when calling useRecaptcha() inside setup() function in Vue 3 (Composition API):

import { useRecaptcha } from 'vue-recaptcha-v3';

export default {
  ...,
  setup() {
    const { executeRecaptcha, recaptchaLoaded } = useRecaptcha(); // => TypeError: Object(...) is not a function
  }
}

/*
"vue": "^3.0.0",
"vue-recaptcha-v3": "^2.0.0",
*/

I've strictly followed the guideline, not sure why it goes wrong...

CSP Issue

In my application, CSP headers are enabled so it blocks unsafe urls.
is there any option to handle it?

Using with Nuxt3

Hey I couldn't find a discussion section in this repo but wanted to place this here in case someone that is using Nuxt 3 needed to make use of this package.
I have a stackblitz link of me using the vue-recaptcha-v3 package with both the composition api and a composable which I prefer since I needed to use the same functionality in a few components: https://stackblitz.com/edit/nuxt-starter-qmmsxd

In case the link is no longer working here is the composable and using it in a template

Vue Template:

<template>
  <div>Token: {{ token }} <br /></div>
</template>
<script>
export default {
  setup() {
    const token = ref('');
    return { token };
  },
  async mounted() {
    this.token = await useVueRecaptcha();
  },
};
</script>

Composable:

import { VueReCaptcha, useReCaptcha } from 'vue-recaptcha-v3';
import { useNuxtApp } from '#app';

export const useVueRecaptcha = async () => {
  const { vueApp } = useNuxtApp();
  vueApp.use(VueReCaptcha, {
    siteKey: '',
    loaderOptions: {
      autoHideBadge: true,
    },
  });
  const { executeRecaptcha, recaptchaLoaded } = useReCaptcha();
  await recaptchaLoaded();
  return await executeRecaptcha('login');
};

If you only need this in one component and don't need a composable you can setup a component like this

<template>
  <div>Component Token: {{ componentToken }}</div>
</template>
<script>
import { VueReCaptcha, useReCaptcha } from 'vue-recaptcha-v3';
export default {
  setup() {
    const { vueApp } = useNuxtApp();
    const componentToken = ref('');
    vueApp.use(VueReCaptcha, {
      siteKey: '',
      loaderOptions: {
        autoHideBadge: true,
      },
    });
    return { componentToken };
  },
  async mounted() {
    const { executeRecaptcha, recaptchaLoaded } = useReCaptcha();
    await recaptchaLoaded();
    this.componentToken = await executeRecaptcha('login');
  },
};
</script>

Vue3 CLI Projekt with Composition API and TS

Hey, I am trying to get this to to work but for some reason I am failing!

I simply created a fresh project and tried to fit the example in:

main.ts look like:

import { createApp } from "vue";
import App from "./App.vue";
import { VueReCaptcha } from "vue-recaptcha-v3";

const app = createApp(App);

app.use(VueReCaptcha, { siteKey: "my-key" });
app.mount("#app");

HelloWorld.vue looks like:

plate>
  <div class="hello">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useReCaptcha } from "vue-recaptcha-v3";

export default defineComponent({
  name: "HelloWorld",
  props: {
    msg: {
      type: String,
      default: "Test"
    }
  },
  setup() {
    const { executeRecaptcha, recaptchaLoaded } = useReCaptcha();

    const recaptcha = async () => {
      // (optional) Wait until recaptcha has been loaded.
      await recaptchaLoaded();

      // Execute reCAPTCHA with action "login".
      const token = await executeRecaptcha("login");

      // Do stuff with the received token.
    }

    return {
      recaptcha
    }
  }
});
</script>

output:

ERROR in src/components/HelloWorld.vue:9:10
TS2724: Module '"../../node_modules/vue-recaptcha-v3/dist/ReCaptchaVuePlugin"' has no exported member 'useRecaptcha'. Did you mean 'useReCaptcha'?
     7 | <script lang="ts">
     8 | import { defineComponent } from "vue";
  >  9 | import { useRecaptcha } from "vue-recaptcha-v3";
       |          ^^^^^^^^^^^^
    10 | 
    11 | export default defineComponent({
    12 |   name: "HelloWorld",

so far...

Error "incorrect-captcha-sol" and "timeout-or-duplicate"

Hi,

I'm using vue-recaptcha-v3 1.9.0 in a production Vue app.

Sometimes, i'm getting this error when we validate the token:

"incorrect-captcha-sol"

The token is significantly different. For instance, this is a valid token:

"03AGdB...."

But the invalid token starts with:
"HFb2Z...."

I have no idea why is wrong.

But sometimes, there are another problem with "timeout-or-duplicate" error.

I don't think the problem is a "timeout" because the token is generated when the user clicks the button and the request takes miliseconds. On the other hand, i find the token once in the logs, so if it was a duplicate, it should come out repeated in the logs.

This is the code:

  import { VueReCaptcha } from 'vue-recaptcha-v3'
...
   async findMovements (clear: boolean) {
      const token = await this.$recaptcha('movements')
      const request = {
        clear,
        callback: () => Utils.modals.showErrorModal({}),
        token
      }
      await this.$store.dispatch('movements/findMovements', request)
    },

The secret keys are correct. And the most important, only fails "some times" but not every day and not always.

Thanks in advance.

issue vue_1.ref is not a function

Hi, when I want to just set up this package as this guideline everything goes wrong. and I got this error ReCaptchaVuePlugin.js?7eae:49 Uncaught TypeError: vue_1.ref is not a function. any way to solve this problem?

timeout-or duplicate error

i tried to submit some form to server
then the form was validated on server side and asked client to fill some data
when i submitted the form again recaptcha raise timeout-or duplicate error
here is my script code at GoogleRecaptcaV3.vue file

export default {
name:'GoogleRecaptcaV3',
props: {
action: {
type: String,
required: true
}
},
created() {
this.recaptcha();
},
methods: {
// setting for vue 2.x
async recaptcha() {
// (optional) Wait until recaptcha has been loaded.
await this.$recaptchaLoaded()
// Execute reCAPTCHA with action "appoinmentRequest".
const token = await this.$recaptcha(this.action)
this.tokenKey = token;
},
},
}

inline example

Hi,

I'm trying to render the badge inline (because it is hidden by the footer), but it does not work. Probably, I'm doing it wrong. Can you give me some example or hint?

I register the plugin like:

import Vue from "vue";
import { VueReCaptcha } from "vue-recaptcha-v3";

Vue.use(VueReCaptcha, {
  siteKey: process.env.RECAPTCHA_PUBLIC_KEY,
  loaderOptions: {
    useRecaptchaNet: true,
    autoHideBadge: false
  },
  explicitRenderParameters: {
    container: 'inline-badge',
    badge: 'inline',
    size: 'invisible'
  }
});

and use it like:

<template>
  <v-container>
   <div id="inline-badge"></div>
   <v-btn @click="submit">Suche</v-btn>
  </v-container>
</template>

Property 'executeRecaptcha' does not exist on type 'IReCaptchaComposition | undefined'

This library does not work as documented. I have followed all the instructions for configuring with Vue 3 composition API, this is what I get:

ERROR in src/components/ReCaptchaV3.vue:32:15
TS2339: Property 'executeRecaptcha' does not exist on type 'IReCaptchaComposition | undefined'.
    30 |     setup(props, { emit }) {
    31 |
  > 32 |       const { executeRecaptcha, recaptchaLoaded } = useReCaptcha();
       |               ^^^^^^^^^^^^^^^^
    33 |
    34 |       async function validate() {


ERROR in src/components/ReCaptchaV3.vue:32:33
TS2339: Property 'recaptchaLoaded' does not exist on type 'IReCaptchaComposition | undefined'.
    30 |     setup(props, { emit }) {
    31 |
  > 32 |       const { executeRecaptcha, recaptchaLoaded } = useReCaptcha();

not working on mobile (with cordova)

On both iphone and android app built with vue & cordova, it shows the msg "could not connect to recaptcha service, please check your internet connection and reload to get reCaptcha challenge".

If I kill the app process and restart, the error msg will disappear. but if I just put the app into sleep, and come back to it, the error msg will appear again. so I have to kill the app again.

The same code base works fine on browser.

How do I display the captcha icon only on certain pages (VUE reCAPTCHA-v3)?

I use this package : https://www.npmjs.com/package/vue-recaptcha-v3. It get from this github

I add on my main.js :

import { VueReCaptcha } from 'vue-recaptcha-v3'

Vue.use(VueReCaptcha, { siteKey: 'xxxxxxx' })

I add this code :

await this.$recaptcha('login').then((token) => {
    recaptcha = token
})

to my component to get token from google recapchta

My problem is the captcha icon in the lower right corner appears on all pages

enter image description here

I want it to only appear in certain components

Maybe I must to change this : Vue.use(VueReCaptcha, { siteKey: 'xxxxxxxxxxxxxxxxx' }). Seems it still mounting to Vue.use. I want to mount to a certain component instead of vue root instance

How can I solve this problem?

Uncaught (in promise) null

When I use the vue-recaptcha-v3 with Webpack (^4.31.0) and VueJS (^2.3.0), after build the project, the following error promise has been occurs.

The code:

import { VueReCaptcha } from 'vue-recaptcha-v3';
Vue.use(VueReCaptcha, { siteKey: 'my_key' });

export default {
  name: 'my-component',
  methods: {
    get_recaptcha() {
      this.$recaptcha('social').then((token) => {
        this.load_result(token);
      });
    }
  }
};

The following error on console browser:

my-component:1 Uncaught (in promise) null
Promise.then (async)
get_recaptcha @ custom.js:34
keyup @ custom.js:48
We @ custom.js:19
n @ custom.js:19
a._wrapper @ custom.js:19

Any ideas from this?

"Cannot read property get of undefined" errors

At work we're seeing thousands of errors reported through Sentry that say "Cannot read property get of undefined"

Environment

OS name and version: Windows and Mac

google/recaptcha version: Latest as served by https://www.recaptcha.net/recaptcha/api.js

Here's a sample of browser occurances:
56.70% | Chrome 89.0.4389
14.43% | Chrome 75.0.3770
7.22% | Chrome 86.0.4240
6.19% | Sogou Explorer 1.0
3.09% | Chrome 78.0.3904
3.09% | Chrome 88.0.4324
3.09% | Chrome 81.0.4044
2.06% | Chrome 85.0.4183
1.03% | Chrome 79.0.3945
1.03% | Chrome 91.0.4442
1.03% | Chrome 80.0.3987
1.03% | Chrome 87.0.4280

All of the error messages are like the following, but sometimes it's k.get, j.get, etc.

TypeError: Cannot read property 'get' of undefined
arguments: [{"message":"Cannot read property 'get' of undefined","name":"TypeError","stack":"TypeError: Cannot read property 'get' of undefined\n at Array. (https://www.gstatic.com/recaptcha/releases/bfvuz6tShG5aoZp4K4zPVf5t/recaptcha__zh_tw.js:106:312)\n at https://www.gstatic.com/recaptcha/releases/bfvuz6tShG5aoZp4K4zPVf5t/recaptcha__zh_tw.js:215:83\n at t.

"TypeError: Cannot read property 'get' of undefined\n at Array. (https://www.gstatic.com/recaptcha/releases/bfvuz6tShG5aoZp4K4zPVf5t/recaptcha__en.js:43:44)\n at https://www.gstatic.com/recaptcha/releases/bfvuz6tShG5aoZp4K4zPVf5t/recaptcha__en.js:310:384\n at t.

Sometimes I just see: TypeError: J is undefined

And here's my console output when testing this in development:

TypeError: Cannot read property 'get' of undefined
    at Array.<anonymous> (recaptcha__en.js:formatted:791)
    at recaptcha__en.js:formatted:6924
    at ReCaptchaInstance.eval (ReCaptchaInstance.js?b3e0:49)
    at step (ReCaptchaInstance.js?b3e0:33)
    at Object.eval [as next] (ReCaptchaInstance.js?b3e0:14)
    at eval (ReCaptchaInstance.js?b3e0:8)
    at new Promise (<anonymous>)
    at __awaiter (ReCaptchaInstance.js?b3e0:4)
    at ReCaptchaInstance.execute (ReCaptchaInstance.js?b3e0:47)
    at eval (ReCaptchaVuePlugin.js?760d:59)

Error with sitekey

I got the error 'Invalid site key or not loaded in api.js: ', but I don't know what I have done wronge.

this.$recaptcha is not a function"

error: this.$recaptcha is not a function"

index.js:
############################
import Vue from 'vue'

import { sync } from 'vuex-router-sync'
// store
import store from "./store.js"
......
import { VueReCaptcha } from "vue-recaptcha-v3"
Vue.use(VueReCaptcha,{siteKey:"6LdwmHcUAAAAAH2jppzD3vcK3f7Rr8H7Krm1-TMg"})
############################
components:
this.$recaptcha("login").then((token) => {
console.log("谷歌Token:"+ token)
})

Verify the token ?

This is really nice but how do I verify the token? Did you forget the main point in the example 😅 ?

Allow late configuration: siteKey

I don't have the siteKey ready with DOMContentLoaded, but rather later.
I do not want to delay initialization of the whole app for this plugin.

Wondering why this isn't possible here. Am I missing something?
Currently testing this implementation (no real Vue integration though..):

// Not using vue-recaptcha-v3, because it wants the siteKey for initial siteload
import { load as loadReCaptcha, ReCaptchaInstance } from "recaptcha-v3";
import { IReCaptchaLoaderOptions } from "recaptcha-v3/dist/ReCaptchaLoader";

// For a more verbose implementation check:
// https://github.com/AurityLab/vue-recaptcha-v3/blob/master/src/ReCaptchaVuePlugin.ts

export async function reCaptcha(action: string, siteKey: string, loaderOptions: IReCaptchaLoaderOptions) {
  const wrapper = await loadReCaptcha(siteKey, loaderOptions);
  // TODO cache or preload wrapper?
  const token = await wrapper.execute(action);
  console.log("reCaptcha token", token);
  return token;
}

CSP violation in production

I host my VueJS SPA app in Azure. I get the following message when the app is loaded.

Refused to load the script 'https://www.google.com/recaptcha/api.js?render=explicit' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

reCaptcha docs recommend:
We recommend using the nonce-based approach documented with CSP3. Make sure to include your nonce in the reCAPTCHA api.js script tag, and we'll handle the rest.

How can I accomplish that?

Vue 3.0 composition

Hi!

I think the Vue 3.0 composition example is not clear. What happens when I want to use reCAPTCHA in a specific component. Should I call use(...) at the app level (ie main.ts)?

I tried this and got undefined when calling useReCaptcha().

I'm using a workaround, but I think this can be improved.

Thanks!

Vue 3 Support

With Vue3 on the horizon, this library should probably support it. I've gotten started with Vue 3 in one of my projects, so I'll try and fork this and open a PR when I have time.

Typescript

Looks like this library is missing an install method?

import { VueReCaptcha } from 'vue-recaptcha-v3';

createApp(App)
  .use(VueReCaptcha, { siteKey: '<token>' })
  .mount('#app');
Argument of type '(Vue: typeof import("<project>/node_modules/vue/dist/vue"), options: IReCaptchaOptions) => void' is not assignable to parameter of type 'Plugin_2'.
  Type '(Vue: typeof import("<project>/node_modules/vue/dist/vue"), options: IReCaptchaOptions) => void' is not assignable to type 'PluginInstallFunction & { install?: PluginInstallFunction | undefined; }'.
    Type '(Vue: typeof import("<project>/node_modules/vue/dist/vue"), options: IReCaptchaOptions) => void' is not assignable to type 'PluginInstallFunction'.
      Types of parameters 'Vue' and 'app' are incompatible.
        Type 'App<any>' is missing the following properties from type 'typeof import("node_modules/vue/dist/vue")': compile, useCssModule, useCssVars, createApp, and 104 more.

Usage

If you ignore the TS error and continue on, you get an error at runtime because there is no longer a default export from vue:

Uncaught TypeError: Vue.prototype is undefined
    > VueReCaptcha ReCaptchaVuePlugin.js:46

hideBadge and showBadge methods do not exist

The README indicates that there should be methods called hideBadge and showBadge:

Screen Shot 2022-01-10 at 4 18 11 PM

But when I try to do this.$recaptchaInstance.showBadge() inside my component, I can an error that says the methods do not exist. I can't see them defined anywhere in this repo; maybe it's a remnant of old code?

How to render verification popup?

every request receives a token which is checked on the backend and I get success, but I have never been able to see the verification popup window.
Should not, at least every now and then, pop up a popup window?

Cannot use recaptcha on a specific component

I would like to implement recaptcha only to login and register component, so I wrote the following code:

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Credentials, ApiError } from "../types/api";
import Vue from "vue";
import { VueReCaptcha } from "vue-recaptcha-v3";

export default defineComponent({
name: "Register",
components: {
    VueReCaptcha,
},
mounted() {
    VueReCaptcha(Vue, { siteKey: "CAPTCHA_SITE_KEY" });
},
setup() {
    const initialState: Credentials = {
    username: "",
    email: "",
    password: "",
    password2: "",
    };

    const data = reactive<Credentials>({ ...initialState });
    const validate = reactive<Credentials>({ ...initialState });

    const alertMessage = ref("");

    const router = useRouter();

    const submit = async () => {
    Object.assign(validate, initialState);
    alertMessage.value = "";

    const res = await fetch(`api/auth/register`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data),
    });

    if (!res.ok) {
        const response = await res.json();

        // lista di errori
        if (response.errors) {
        const errors: ApiError[] = response.errors;

        for (const err of errors) {
            validate[err.param] = err.msg;
        }
        } else {
        alertMessage.value = (response as ApiError).msg;
        }
    }

    /*
    if (res.text === 200) {
        await router.push("/login");
    }*/
    };

    return {
    data,
    validate,
    alertMessage,
    //recaptcha,
    submit,
    };
},
});
</script>

the problem is that I get the following error:

could someone tell me what I did wrong?

Localization

The browser language is English, but Recaptcha still in the Russian language.

I can pass language param like this?
Vue.use(VueReCaptcha, { siteKey: '', loaderOptions: {renderParameters: {"hl": "en"}} })

I tried, but it doesn't work.

Usage with Vue CLI 3: Docs need expansion

I would like to update the docs to help folks use this plugin with the Vue CLI. It seems like the obvious injection method in Vue CLI is loading the recaptcha script as soon as the application loads:

main.js

import Vue from 'vue';
import App from './App.vue';
import router from './router';

import { VueReCaptcha } from 'vue-recaptcha-v3';

Vue.config.productionTip = false;

Vue.use(VueReCaptcha, { siteKey: '<site-key>' });

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

However, I am trying to figure out the best way to inject the script within a specific component on a specific page. I have this so far:

signup.vue

<script>
import Vue from 'vue';
import { VueReCaptcha } from 'vue-recaptcha-v3';

export default {
  name: 'SignUp',
  data() {
    ...
  },
  created() {
    // Run recaptcha script on signup page
    if (this.$recaptchaInstance) {
      this.$recaptchaInstance.showBadge();
    } else {
      Vue.use(VueReCaptcha, {
        siteKey: '<site-key>',
      });
    }
  },
  destroyed() {
    this.$recaptchaInstance.hideBadge();
  },
  computed: {
    ...
  },
  methods: {
    ...
  }
};
</script>

Is it bad practice to load the recaptcha within a specific view instead of the app level? If not, then what is the best way to inject the recaptcha at the component level?

vue_1.ref is not a function - Error when loading through the Client API in Gridsome

When I trying to use this plugin with Gridsome, I figured the proper way to load it is in the main.js file like this:

import { VueReCaptcha } from 'vue-recaptcha-v3'

// The Client API can be used here. Learn more: gridsome.org/docs/client-api
export default function (Vue) {
  Vue.component('Layout', DefaultLayout)
  Vue.use(VueReCaptcha, { siteKey: '...' })
}

When I do that though, it seems that the import {... ref, ...} from 'vue' in the ReCaptchaVuePlugin.ts file fails, specifically the line const isLoaded = ref(false).

Anyone know how to fix?

Here's the documentation for the Client API: https://gridsome.org/docs/client-api/

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.