Grecaptcha reset не работает

Ошибка: клиенты reCAPTCHA не существуют (reCAPTCHA v3)

Я интегрировал reCAPTCHA v3 в одну из моих форм. В режиме onload в правом нижнем углу отображается токен и логотип Google CAPTCHA. Но когда я отправляю форму, в консоли появляется сообщение об ошибке «Ошибка: клиенты reCAPTCHA не существуют». Также, похоже, данные не извлекаются с помощью «g-recaptcha-response» и $ _POST [«g-recaptcha-response»] остается пустым.

Вот пример кода:

Он не производит никакого «g-recaptcha-response» при отправке формы.

Я не знаю много о Google ReCaptcha. Я следовал предоставленной ими документации и правильно использовал сайт и секретный ключ.

Кто-нибудь, пожалуйста, скажите мне, где может быть проблема и какое возможное решение?

5 ответов

Вы пытались загрузить скрипт, прежде чем отправлять запрос?

Я полагаю, что эта ошибка возникает, когда reCaptcha api.js загружается, но ваш контейнер еще не представлен на странице (по крайней мере, для v2). Эта ошибка возникала в приложении React при переходе на страницу, а не при ее загрузке в качестве первого. Вместо того, чтобы использовать render=explicit и использовать глобальное пространство имен onLoadCallback , я смог разрешить его, вручную отобразив элемент captcha.

Это также происходит в Recaptcha 2, прежде чем пользователь взаимодействует с ним. Итак, у меня есть кнопка отправки, которая запускает функцию JS, которая проверяет значение recaptcha. Чтобы решить проблему отсутствия клиента, я сделал:

Затем объект данных отправляется внутреннему сценарию, который проверяет recaptcha. Серверная часть также проверяет, является ли поле пустым.

Когда я столкнулся с этой проблемой с reCAPTCHA v3, это было потому, что я не передал ему правильный ключ сайта.

Источник

Как перезагрузить виджет Google recaptcha после отправки пользователем недопустимых входных данных

У меня есть регистрационная форма с новым виджетом Google recaptcha на нем. Когда пользователь отправляет информацию, мы проверяем проверку с помощью javascript и возвращаем проблемы на страницу (например: «пожалуйста, используйте действительный номер телефона»). однако, поскольку страница не перезагружается, когда пользователь вводит правильную информацию и переходит к отправке снова (без необходимости повторения recaptcha). recaptcha больше не действителен, и они не могут отправить без перезагрузки страницы.

Читайте также:  Если не работают яичники что это значит

есть ли хорошее решение для это? могу ли я как-то перезагрузить виджет? я попробовал грекапчу.рендер, но он ничего не сделал.

когда я пытаюсь отобразить виджет, он говорит «элемент-заполнитель должен быть пустым»

Я попытался опорожнить элемент, который, казалось, работал ($(‘.G-recaptcha’).empty ();), а затем рендеринга, но он по-прежнему бросил ту же ошибку.

11 ответов

метод, который вы ищете является grecaptcha.reset()

однако, чтобы эта функция работала, вы должны явно отобразить reCaptacha следующим образом:

Если вы используете grecaptcha.рендеринг с помощью jQuery убедитесь, что вы фактически устанавливаете элемент DOM вместо элемента jQuery:

этой будет работы:

но это не:

я смог сделать это только с помощью:

вот код, чтобы сопровождать ответ @tzafar:

в моем случае, my-captcha идентификатор div внутри Bootstrap модальные. Я бегу!—4—> в обработчике событий для модального shown.bs.modal событие. В первый раз, он инициализирует капчи. На последующих показах модального он сбрасывает его.

кроме того, обратите внимание, что вы можете быстро проверить, что вы получаете новую капчу, распечатав значение завершенной капчи:

вы не должны увидеть дважды одно и то же значение.

Personnaly я сбросил свой html-контент элемента с

после этого я перезагружаю recaptcha, используя

которые загружают содержимое recaptcha на ваш

ваше событие reCAPTCHA render js должно вызываться только один раз в скрипте, ваш код recaptcha недействителен, если grecaptcha.render событие js вызывается второй раз в скрипте. Вы должны проверить свой код, чтобы он не вызывал grecaptcha.render функция второй раз при проверке проверки.

в консоли, вы увидите Uncaught ReferenceError: Recaptcha is not defined сообщение об ошибке, которое указывает на проблему со скриптом reCAPTCHA. Это вызвано из — за плохого url-адреса на странице — http://api.recaptcha.net/js/recaptcha_ajax.js . Google обновил reCAPTCHA и переместил расположение скрипта в http://www.google.com/recaptcha/api/js/recaptcha_ajax.js .

также проверьте этот пост

Если вы используете новый recaptcha 2.0, используйте это: для код:

Источник

example reset captcha #24

Comments

DmitrySkibitsky commented Apr 5, 2018

Please give an example of how you reset the captcha if there are several of them on the page. I have not tried it all the same.

The text was updated successfully, but these errors were encountered:

DmitrySkibitsky commented Apr 5, 2018 •

How to reset a specific captcha?

DmitrySkibitsky commented Apr 5, 2018

We had to change the generation of js. Assign variable + i = grecaptcha.render. And after doing grecaptcha.reset (variable + i);

thinhbuzz commented Apr 6, 2018

i think will be create buzzNoCaptchaWidgetIds js variable and assign widget with key is html id.
i will flow document

Читайте также:  Трубка вентури не работает

JanisE commented Apr 9, 2018

Looking forward to a fix. Cannot use this package while resetting not supported.

thinhbuzz commented Apr 9, 2018

feature has been added in v2.1.8, you can try example on examples folder
I hope useful to you

DmitrySkibitsky commented Apr 9, 2018 •

This is how I had to fix the source package.

But this in haste, as it was necessary to quickly fix the reset.
A bit later I plan to add a more customized solution. Where in $attributes the name of the widget will be transferred and after that the widget will be sent to the reset function, which should be reset for example after the Ajax request failed validation.

thinhbuzz commented Apr 9, 2018

you want show multiple captcha on page and able reset it? check here multiple.blade.php

DmitrySkibitsky commented Apr 9, 2018

I apologize. Everything, revised examples and changes. Thank you.

DmitrySkibitsky commented Apr 9, 2018

You can close it.) The problem is solved.

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

How to reset multiple captchas? #74

Comments

madaolex commented Aug 24, 2018 •

Hi!
How can I reset captcha by opt_widget_id (as they say on google captcha docs)?

When I try to reset captcha by attribute ‘id’ in div with ‘g-recaptcha’ class, it does not work.
On StackOverflow there is a answer with that solution:

but in
\Arcanedev\NoCaptcha\NoCaptcha::renderCaptchas
function you do render captchas without saving widget ID to anywhere

Maybe there is some function to get widgetID?

The text was updated successfully, but these errors were encountered:

madaolex commented Aug 24, 2018 •

Well I can save widgetID to variable in this function, but it works only if «-» symbol replace to «_».

and then use that variable in js like this

It works, but maybe there is some out-of-box function?

arcanedev-maroc commented Aug 24, 2018

I’m working on it 👍

arcanedev-maroc commented Aug 24, 2018 •

The following PR allows you to access the rendered captchas by using the window.noCaptcha.renderedCaptchas (global) variable.

Try to make the same changes as this class and tell me if it fixes your issue!

madaolex commented Aug 24, 2018

Thank you, it worked!

But may I ask you, maybe you can add captchas in array like this?

Now we can apply to id of captcha using name as a key, no need to foreach whole array if we need to reset just one captcha.

It is necessary to check keys in array before reset or it can crash, though.
I just want to know your opinion, because I do not have much experience.

Читайте также:  Где отремонтировать ноутбук асус

arcanedev-maroc commented Aug 24, 2018 •

But I think I can extend the window.noCaptcha functionalities. Stay tuned

arcanedev-maroc commented Aug 28, 2018

I’ve added a new JS API to manage the captchas with ease:

You can’t perform that action at this time.

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.

Источник

How can I reload reCaptcha v3?

I saw Google Docs and didn’t found information about reloading reCaptcha v3. https://developers.google.com/recaptcha/docs/v3

How can I do that?

2 Answers 2

reCaptcha V3 in an invisible captcha, it automagically detects user behaviors and rate it, no need to reload or user’s direct interaction with any UI.

reCAPTCHA v3 returns a score for each request without user friction. The score is based on interactions with your site and enables you to take an appropriate action for your site.

reCAPTCHA v2 reset

reCAPTCHA v3 reset

Calling the grecaptch.execute() function that gets rendered on the page , will reset the value by the looks. (Google Recaptcha V3 — Widget Id when loading captcha through URL)

Note you will need to adjust all your values accordingly.

You can test it by copying this and pasting in the chrome console. After pressing enter it then changes the value of the hidden field.

Make sure you are refreshing your token with each subsequent postback or call to Google.

In my case, using reCAPTCHAv3, I was saving the token to an ASP.NET HiddenField server control for discovery on the back end. However, this control was not getting updated with the new token on subsequent postbacks because of a mistake in my javascript code (I was only refreshing the token if the HiddenField was not blank, which it wasn’t on postbacks). I discovered my error by comparing the JSON results returned by Google and discovering the error code «timeout-or-duplicate» on the second response.

The solution was to clear the HiddenField value in JavaScript before calling Google. Hope this helps someone else having this same issue.

Not the answer you’re looking for? Browse other questions tagged javascript recaptcha or ask your own question.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.10.19.40496

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью