others - Javascript - Promises如何处理谷歌的Recaptcha?

它在最新版本的Firefox和Chrome中都失败,错误是"uncaught exception:undefined "(Firefox) " uncaught (in promise) undefined " (Chrome) and traces back to the line where reject() is called.

我做错什么了?有没有别的方法来做这个?


<script>


var onloadCallback, onerrorCallback;


var promise = new Promise(function(resolve, reject) {


 onerrorCallback = function() {


 reject();


 }


 onloadCallback = function() {


 var form = document.createElement('form'),


 recaptcha = document.createElement('div');


 form.method = 'post';


 resolve(grecaptcha.render(recaptcha, {


 sitekey: 'INVISIBLE RECAPTCHA SITE KEY',


 size: 'invisible',


 callback: function() {


 form.submit()


 }


 }));


 form.appendChild(recaptcha);


 document.body.appendChild(form);


 }


})



function userClick() {


 promise


 .then(grecaptcha.execute)


 .catch(function(){alert('Error')});


}


</script>


<script async defer src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en" onerror="onerrorCallback()"></script>


<p>Please <a href="javascript:userClick()">click here</a> to solve the recaptcha</p>



时间: 作者:

我发现了问题,下面是我修复的方法:


<script>


var onloadCallback, onerrorCallback;


var promise = new Promise(function(resolve, reject) {


 onerrorCallback = function() {


 reject();


 }


 onloadCallback = function() {


 var form = document.createElement('form'),


 recaptcha = document.createElement('div');


 form.method = 'post';


 resolve(grecaptcha.render(recaptcha, {


 sitekey: 'INVISIBLE RECAPTCHA SITE KEY',


 size: 'invisible',


 callback: function() {


 form.submit()


 }


 }));


 form.appendChild(recaptcha);


 document.body.appendChild(form);


 }


})



function userClick() {


 promise


 .then(function(id) {


 grecaptcha.execute(id);


 })


 .catch(function(){alert('Error')});


}


</script>


<script async defer src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit&hl=en" onerror="onerrorCallback()"></script>


<p>Please <a href="javascript:userClick()">click here</a> to solve the recaptcha</p>



问题在then()调用中,由于grecaptcha未定义,JavaScript已停止,并且从未发出catch()调用,控制台上打印的错误消息与此无关。

作者:
...