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>
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