reCaptcha + RequireJS [英] reCaptcha + RequireJS

查看:35
本文介绍了reCaptcha + RequireJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 requirejs 导入 recaptcha.我已经尝试了几件事,但没有任何效果.

How can I import recaptcha using requirejs. I already tryed several things and nothing works.

我需要这样做才能在加载后使用 reCaptcha 的 render 方法自己渲染它.

I need do that to be able to render it by my own using the method render of reCaptcha once it has been loaded.

require.config({
    paths: {
        'recaptcha': 'http://www.google.com/recaptcha/api'
    }
});

require( ['recaptcha'], function( recaptcha ) {
    // do something with recaptcha
    // recaptcha.render  /// at this point recaptcha is undefined
  console.log(recaptcha);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.2.0/require.min.js"></script>

推荐答案

是的,我有一个解决方案.所以最终发生的情况是,recaptcha 无法呈现,直到它从谷歌 api 加载了它需要的内容.

Yes I have a solution for you. So what ends up happening is that recaptcha can't render until it has loaded what it needs from the google api.

所以你需要做的是以下(也不要在你的路径中使用 http/https):

So what you need to do is the following (also don't use http/https in your paths):

require.config({
  paths: {
      'recaptcha': '//www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit'
  }
});

现在这将允许在从谷歌 API 下载必要的库后执行回调.不幸的是,这个回调需要是全局的.

Now that will allow a callback to be executed after the necessary libraries have been downloaded from the google API. This callback needs to be global unfortunately.

JS

var requireConfig = {
 paths: {
  'recaptcha': '//www.google.com/recaptcha/api.js?    onload=onloadCallback&render=explicit'
 }
};

function render(id) {
  console.log('[info] - render');
  recaptchaClientId = grecaptcha.render(id, {
    'sitekey': '6LdntQgUAAAAANdffhZl0tIHw0fqT3MwNOlAI-xY',
    'theme': 'light'
  });
};
window.renderRecaptcha = render;

var onloadCallback = function() {
  console.log('[info] - onLoadCallback');
  if (!document.getElementById('g-recaptcha')) {
    return;
  }
  window.renderRecaptcha('g-recaptcha');
};

requirejs.config(requireConfig);

require(['recaptcha'], function(recaptcha) {

});

HTML

<body>
    <form action="?" method="POST">
      <div id="g-recaptcha"></div>
      <br/>
      <input type="submit" value="Submit">
    </form>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.js">    </script>


</body>

希望对你有用!

示例链接:https://jsbin.com/kowepo/edit?html、js、控制台、输出

这篇关于reCaptcha + RequireJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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