如何使用需求导入recaptcha。我已经试过几件事了,但都没有用。
我需要这样做,以便能够使用reCaptcha的方法在加载之后使用自己的方法来呈现它。
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>
发布于 2016-10-06 15:19:05
是的我有个解决办法给你。因此,最终发生的情况是,在从google加载了所需的内容之前,recaptcha无法呈现。
因此,您需要做的是:(也不要在路径中使用http/https ):
require.config({
paths: {
'recaptcha': '//www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit'
}
});
现在,这将允许在从google下载了必要的库之后执行回调。不幸的是,这种回调必须是全局的。
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>
我希望这对你有用!
发布于 2020-03-12 17:41:12
我知道这个问题有点老,但我最近在我的项目中发现了另一个不需要创建全局方法的解决方案。这个解决方案最终成为OP第一次尝试在RequireJS中使用Google reCaptcha的一个非常简单的补充。
在main.js
中,添加以下内容:(与OP完全相同)
require.config({
paths: {
'recaptcha': 'http://www.google.com/recaptcha/api'
}
});
在执行显式呈现的JS文件中,执行以下操作:
require( ['recaptcha'], function(recaptcha) {
// render when recaptcha is ready
// injecting recaptcha here will give access to the grecaptcha object and it's ready method
grecaptcha.ready(function()
grecaptcha.render('elementId', {
'sitekey': 'SITE_KEY',
'callback': someCallbackMethod
});
);
});
这对我有效,我相信这是一个更清洁的解决方案!
https://stackoverflow.com/questions/39854128
复制相似问题