reCaptcha + RequireJS

廉价感情. 提交于 2020-01-03 21:09:55

问题


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

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>

回答1:


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.

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'
  }
});

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>

I hope that works for you!

Link to Example: https://jsbin.com/kowepo/edit?html,js,console,output



来源:https://stackoverflow.com/questions/39854128/recaptcha-requirejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!