Dea*_*ean 2 javascript jquery recaptcha sweetalert
我正在处理一个需要在 SweetAlert 弹出框中进行 reCaptcha 验证的功能,但出现以下错误:
未捕获的错误:reCAPTCHA 占位符元素必须是元素或 ID
我一直在调查导致此错误的原因,我注意到这是因为该元素在尝试生成 reCaptcha 元素时尚未加载。
function confirmBox() {
var div = document.createElement('div');
div.id = 'recaptcha';
div.onload = genRecaptcha();
swal({
title: "Are you sure?",
content: div,
icon: "warning",
buttons: true,
dangerMode: true,
})
}
function genRecaptcha() {
console.log($('#recaptcha').attr('id'));
grecaptcha.render('recaptcha', {
'sitekey': '6Le2ZFUUAAAAAEV4IM_5weEnXg4gVplan2Atgiaj'
});
}
$('#btn1').click(confirmBox);Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js"></script>
<button id="btn1">Submit</button>Run Code Online (Sandbox Code Playgroud)
我正在尝试将genRecaptcha函数与onload触发器一起放置,但似乎无法获取元素。
弹窗满载后有什么办法可以执行函数吗?或者我在这里做错了什么?
UPD:这是现场演示:https : //sweetalert2.github.io/recipe-gallery/recaptcha.html
这是SweetAlert2的解决方案- SweetAlert的支持分支:
function showSweetAlertRecaptcha() {
Swal.fire({
title: 'SweetAlert2 + Recaptcha',
html: '<div id="recaptcha"></div>',
willOpen: function() {
grecaptcha.render('recaptcha', {
'sitekey': '6LdvplUUAAAAAK_Y5M_wR7s-UWuiSEdVrv8K-tCq'
});
},
preConfirm: function () {
if (grecaptcha.getResponse().length === 0) {
Swal.showValidationMessage(`Please verify that you're not a robot`)
}
}
})
}Run Code Online (Sandbox Code Playgroud)
#recaptcha > div {
width: auto !important;
margin-bottom: .5em;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://www.google.com/recaptcha/api.js?onload=showSweetAlertRecaptcha"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>Run Code Online (Sandbox Code Playgroud)