SweetAlert 模式窗口中的 Google reCaptcha [英] Google reCaptcha within SweetAlert modal window

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

问题描述

我正在开发一个需要在 SweetAlert 弹出框中进行 reCaptcha 验证的功能,但出现以下错误:

I'm working on a function which requires doing a reCaptcha verification within a SweetAlert popup box, but I'm getting the following error:

未捕获的错误:reCAPTCHA 占位符元素必须是元素或 ID

Uncaught Error: reCAPTCHA placeholder element must be an element or id

我一直在调查导致此错误的原因,我注意到这是因为该元素在尝试生成 reCaptcha 元素时尚未加载.

I've been looking into what's causing this error, and I notice it's because the element hasn't been loaded yet when it tries to generate the reCaptcha element.

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

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

我正在尝试将 genRecaptcha 函数与 onload 触发器一起放置,但它似乎无法获取元素.

I'm trying to put the genRecaptcha function with the onload trigger, but it seems to be unable to get the element.

有没有什么方法可以在弹窗满载后执行函数?还是我在这里做错了什么?

Is there any way to execute the function after the popup box is fully loaded? Or there is something I did wrong here?

推荐答案

使用来自 jquery 而不是使用 .onload

Problem solve by using $(element).ready from jquery instead of using .onload

下面提供的代码段将无法正常运行,因为此站点的 recaptcha 站点密钥无效

function confirmBox() {
    var div = document.createElement('div');
    div.id = 'recaptcha';
    $('#recaptcha').ready(function () {
        console.log($('#recaptcha').attr('id'));
        grecaptcha.render('recaptcha', {
            'sitekey': '6Le2ZFUUAAAAAEV4IM_5weEnXg4gVplan2Atgiaj'
        });
    })

    swal({
        title: "Are you sure?",
        content: div,
        icon: "warning",
        buttons: true,
        dangerMode: true,
    })
}

$('#btn1').click(confirmBox);

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

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

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