首页 > 解决方案 > recaptcha 在 Vue 组件中不起作用。当未加载 grecaptcha 时,grecaptcha.render 不是函数

问题描述

如何在Vue组件中添加grecaptcha onload方法。未加载时grecaptcha.render不是函数

const script = document.createElement("script");
 script.src = `${URL}?render=explicit&hl=TR`;
 script.async = true;
 script.defer = true;
 document.body.appendChild(script);
 this.initReCaptcha();


initReCaptcha: function () {
    setTimeout(function () {
       if (typeof grecaptcha === 'undefined') {
           this.initReCaptcha();
       } else {
          grecaptcha.render('recaptcha', {
          sitekey: 'XXXX',
          callback: this.submit,
          'expired-callback': this.expired
                        });
                    }
                }.bind(this), 100);
            }

当我设置超时 1000 时正在工作。但为时已晚。

标签: javascriptvue.jsrecaptcha

解决方案


recaptcha 脚本已于2018 年 5 月 4 日 9:07:30.349 PM GMT更新(基于 recaptcha 脚本的时间戳)。正在加载 grecaptcha,但是渲染函数有一个延迟,这就是为什么 recaptcha 没有显示在 UI 中(grecaptcha.render 不是一个函数)。可能的解决方法是在尝试加载 recaptcha 之前验证渲染功能。

这是修复:

initReCaptcha: function () {
    setTimeout(function () {
        if (typeof grecaptcha === 'undefined' || typeof grecaptcha.render ==='undefined') {
            this.initReCaptcha();
        } else {
            grecaptcha.render('recaptcha', {
                sitekey: 'XXXX',
                callback: this.submit,
                'expired-callback': this.expired
            });
        }
    }.bind(this), 100);
}

我希望它会帮助你。干杯

**修正了 qRoC 在评论中所写的情况,谢谢。


推荐阅读