隐形的Google Recaptcha和ajax表单 [英] Invisible google Recaptcha and ajax form

查看:667
本文介绍了隐形的Google Recaptcha和ajax表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ajax表单:

 < form id =my_form> 
< input type =textid =field1/>
< input type =submitvalue =submit/>
< / form>

和js代码:

  document.getElementById(my_form)。onsubmit = function(e){
e.preventDefault();

var xhr = new XMLHttpRequest();
// ..............向服务器发送请求

在文档中,它假定一个表单是一个常规表单,而不是ajax。我应该如何将隐形reCaptcha整合到我的ajax表单中?例如:

 < form id =my_form> 
< input type =textid =field1/>
< div class =g-recaptchadata-sitekey =12345data-callback =????>< / div>
< input type =submitvalue =submit/>
< / form>

我应该为数据回调处理程序指定什么?同样,在文档中,数据回调提交表单,但是是一个正常的表单,而我的是ajax。我是否需要数据回调?而是在我的处理程序中调用recaptcha?怎么样?



有render,getResponse和execute,我应该使用哪一个?我同意看不见的recaptcha文档不够全面,我不得不花一些时间来挖掘代码示例。

和可见的recaptcha的文件,然后才能理解如何使用它。



让我们先谈谈recaptcha API:



grecaptcha.render(htmlEl,opt离子,继承)是在页面上呈现验证码HTML的JS API方法。默认情况下,recaptcha脚本会尝试找到任何含有 class =g-recaptcha 的元素并尝试立即渲染,但是这种行为可以通过追加 ?render = explicit query param to recaptcha script src url。您也可能想使用这个api在你的recaptcha .g-recaptcha 元素在加载脚本后的某个时间点附加到DOM上,这个api返回一个可以传递给其他api方法的ID值,但如果没有传递,那么这些api的查找和引用将首先在页面上进行repcaptcha。 p>

grecaptcha.getResponse(optional_id)返回标记,如果标记为空字符串,表示用户尚未验证即用户尚未完成验证码挑战。



grecaptcha.execute(optional_id) api会触发这个api只适用于无形recaptcha。可见的recaptcha challen当用户点击recaptcha模块时触发ges。
$ b

grecaptcha.reset(optional_id)会重置一个挑战,也就是它必须在服务器无法使用recaptcha api服务器验证令牌时进行(因为令牌是一次性使用),但根据您的实施情况,您可能会决定随时重置。





数据回调现在,让我们谈谈数据回调:是一个属性,您可以传递全局名称空间函数的名称,即某些可作为window ['nameOfFunction']访问的函数。每次用户最终传递给服务器的令牌值验证成功时,都会调用此回调函数。这是由 grecaptcha.getResponse()返回的相同标记,因此从技术上讲,您根本不需要此函数。但它可以作为回调,让你知道用户已通过验证,以防万一你需要更新UI或其他东西。



如果由于某种原因,您不希望此回调可以通过窗口命名空间访问,你可以在options对象中使用 callback 键将这个方法传递给 grecaptcha.render()。注意: options.callback 可以接受一个字符串值,相当于在HTML中传递 data-callback 属性,即必须是窗口名称空间中的函数。但是 options.callback 也可以带一个功能值。




现在有一些示例代码:



HTML b
$ b

 < script src =https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoadasync defer>< / script> 

JS

  window.onScriptLoad = function(){
//这个回调一旦被加载,就会被recaptcah / api.js调用。如果我们在脚本src中使用
// render = explicit作为参数,那么我们可以在此处显式地呈现reCaptcha

//元素到渲染不可见captcha in
var htmlEl = document.querySelector('。g-recaptcha');

//验证码选项
var captchaOptions = {
sitekey:'6Lck',
size:'invisible',
//告诉reCaptcha哪个回调以通知用户验证成功。
//如果这个值是字符串,那么它必须是可以通过window ['nameOfFunc'],
访问的函数的名字//并且传递字符串等同于指定data-callback ='nameOfFunc',但是它可以是
//引用实际函数
callback:window.onUserVerified
};

//仅用于隐形类型。如果为true,那么将从html元素的data- *属性读取值,如果它没有通过captchaOptions传递
var inheritFromDataAttr = true;

//现在渲染
recaptchaId = window.grecaptcha.render(htmlEl,captchaOptions,inheritFromDataAttr);
};

//这是从data-callback或render()的options.callback赋值的
window.onUserVerified =函数(令牌){
alert('用户被验证');
console.log('token =',token);
};


//表单提交按钮的单击处理函数
函数onSubmitBtnClick(){
var token = window.grecaptcha.getResponse(recaptchaId);

//如果没有标记,意味着用户尚未验证
if(!token){
//触发验证
window.grecaptcha.execute(recaptchaId) ;
return;
}

var xhrData = {
'g-recaptcha-response':token
// more ajax body / data here
};

//继续将更多的ajax调用数据附加到xhrData,然后再调用ajax调用进程的其余部分
// var xhr = new XMLHttpRequest();
// ... ... .... ... ...
}


I have an ajax form:

  <form id="my_form">
    <input type="text" id="field1" />
    <input type="submit" value="submit" />
  </form>

And js code:

document.getElementById("my_form").onsubmit = function(e) {
  e.preventDefault();

  var xhr = new XMLHttpRequest();
  //.............. send request to a server

In the documentation it assumes that a form is a normal form, not ajax. How exactly should I integrate invisible reCaptcha to my ajax forms? For example:

  <form id="my_form">
    <input type="text" id="field1" />
    <div class="g-recaptcha" data-sitekey="12345" data-callback="????></div>
    <input type="submit" value="submit" />
  </form>

And, in particular, what should I specify for "data-callback" handler? Again, in the documentation it data-callback submits a form, but a normal form, whereas mine is ajax. Do I need "data-callback" at all? Shouldn't I instead call recaptcha inside my handler? How?

There're "render", "getResponse" and "execute". Which one should I use? It's not clear from the documentation.

解决方案

I agree that "invisible" recaptcha documentation is not comprehensive enough. I had to spend some time digging thru code example and documentations of "visible" recaptcha before understanding how to work with this.

Let talk about the recaptcha API first:

grecaptcha.render(htmlEl, options, inherit) is JS API method of rendering the captcha HTML on the page. By default recaptcha script will try to find any element with class="g-recaptcha and try to render immediately, but this behavior can be overridden by appending ?render=explicit query param to recaptcha script src url. You also may want to render the recaptcha html on demand using this api when your recaptcha .g-recaptcha element gets attached to DOM at a point later than when script was loaded. This api returns an ID value that can be passed to other api methods, but if not passed, those api's lookup and reference first repcaptcha on page.

grecaptcha.getResponse(optional_id) returns the token. If token is empty string, it means user has not been validated yet i.e. user hasn't completed the captcha challenge.

grecaptcha.execute(optional_id) api triggers the recaptcha challenge on-demand programmatically. This api is only applicable to "invisible" recaptcha. Visible recaptcha challenges are triggered when user clicks the recaptcha module.

grecaptcha.reset(optional_id) will reset a challenge i.e. it must be done each time server fails to validate the token with recaptcha api server (because tokens are one time use), but depending on your implementation, you may decide to reset any time.

Now, lets talk about data-callback:

data-callback is an attribute where you can pass a name of global namespaced function, i.e. some function which is accessible as window['nameOfFunction']. This callback will get called each time user is successfully validated with a token value that you will eventually be passing to server. This is same token that is returned by grecaptcha.getResponse() so technically you do not need this function at all. But it can serve as callback to let you know user has passed verification in case you need to update UI or something.

If for some reason you do not want this callback to be accessible from window namespace, you can pass this method in options object with callback key to grecaptcha.render(). NOTE: options.callback can take a string value which is equivalent to passing data-callback attribute in HTML, i.e. is must be a function in window namespace. But options.callback can take a "function" value as well.


Now some sample code:

HTML

<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onScriptLoad" async defer></script>

JS

window.onScriptLoad = function () {
    // this callback will be called by recaptcah/api.js once its loaded. If we used
   // render=explicit as param in script src, then we can explicitly render reCaptcha at this point

    // element to "render" invisible captcha in
    var htmlEl = document.querySelector('.g-recaptcha');

    // option to captcha
    var captchaOptions = {
      sitekey: '6Lck',
      size: 'invisible',
      // tell reCaptcha which callback to notify when user is successfully verified.
      // if this value is string, then it must be name of function accessible via window['nameOfFunc'], 
      // and passing string is equivalent to specifying data-callback='nameOfFunc', but it can be
      // reference to an actual function
      callback: window.onUserVerified
  };

    // Only for "invisible" type. if true, will read value from html-element's data-* attribute if its not passed via captchaOptions
    var inheritFromDataAttr = true;

    // now render
    recaptchaId = window.grecaptcha.render(htmlEl, captchaOptions, inheritFromDataAttr);
};

// this is assigned from "data-callback" or render()'s "options.callback"
window.onUserVerified = function (token) {
    alert('User Is verified');
    console.log('token=', token);
};


// click handler for form's submit button
function onSubmitBtnClick () {      
  var token =   window.grecaptcha.getResponse(recaptchaId);

  // if no token, mean user is not validated yet
  if (!token) {
     // trigger validation
     window.grecaptcha.execute(recaptchaId);
     return;
  }

  var xhrData = {
    'g-recaptcha-response': token
    // more ajax body/data here
  };

  // proceed with appending more ajax call data to xhrData and then rest of ajax call process
  // var xhr = new XMLHttpRequest();
  // ... ... .... ... ... 
}

这篇关于隐形的Google Recaptcha和ajax表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆