recaptcha 在 Vue 中不起作用 component.give grecaptcha.render 在 grecaptcha 未加载时不是函数

recaptcha doesn't work in Vue component.give grecaptcha.render is not a function when grecaptcha not loaded

如何在 Vue 中添加 recaptcha onload 方法 component.when 未加载 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.but为时已晚。

我发现从两天前开始,很多人都得到了错误:

 grecaptcha.render is not a function

好吧,这对我有用。也许它可以帮助

中的某个人

我把它分解成和平的,这样你就可以轻松阅读它了:

mounted(){
    if (typeof grecaptcha === "undefined") {
        var script = document.createElement("script");
        script.src = "https://www.google.com/recaptcha/api.js?render=explicit";
        script.onload = this.renderWait;
        document.head.appendChild(script);
    } else this.render();
}

如果没有加载grecaptcha,我将创建一个脚本并等待它加载。 如果是这样,则调用 renderWait

renderWait() {
        setTimeout(() => {
            if (typeof grecaptcha !== "undefined" && typeof grecaptcha.render !== "undefined")  this.render();
            else this.renderWait();
        }, 200);
},

当我们最终完成 grecaptcha 渲染时:

render() {
        const recaptchaDiv = document.createElement('div');
        recaptchaDiv.className = 'outside-badge';
        document.body.appendChild(recaptchaDiv);

        this.widgetId = grecaptcha.render(recaptchaDiv, {
            sitekey: this.sitekey,
            size: "invisible",
            badge: this.badge || "bottomright",
            theme: this.theme || "light",
            callback: token => {
                this.callback(token);
                grecaptcha.reset(this.widgetId);
            }
        });
        this.loaded = true;
 },

也许对你有帮助:)

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

修复如下:

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 在评论中写的条件,谢谢。