页面加载后立即执行不可见的验证码

Invisible captcha executed as soon as page loads

我正在尝试使用 google 的功能来检查页面请求是来自人还是机器人。 通过这个我想包含一个不可见的验证码并在页面加载完成后立即提交验证。 我已经浏览了 google 文档 https://developers.google.com/recaptcha/docs/invisible,正常的示例对我来说工作正常。但是我正在尝试以一种方式调整它 grecaptcha.execute() 在页面加载后立即触发,我尝试使用 window.onload 或 (window).ready( ) 我得到了相同的错误

grecaptcha is not defined

当然我相信是因为grecaptcha脚本没有准备好,事实上如果我设置1秒或2秒的超时,它会执行得很好。

我试图将 "onload" 参数添加到 api.js 但没有成功......顺便说一下 api.js 只是在 HEAD "recaptcha__en.js"

我不需要实际的表格或提交任何联系信息,只需要验证查看页面的对象是人还是机器人

任何 ideas/suggestions 将不胜感激! 谢谢!!

编辑:按要求添加代码:

<html>
<head>
    <script>
        //called only when I set the timeout
        function onSubmit(){
            console.log("Submitted")
        }

        //not being called by the "onload parameter of the api.js script"
        function loadCaptcha(){
          console.log("loaded")
          setTimeout(function(){grecaptcha.execute()},2000)
        }

    </script>
    <script src='https://www.google.com/recaptcha/api.js' async defer></script>
    <!--<script src='https://www.google.com/recaptcha/api.js?onload="loadCaptcha"' async defer></script>----it doesnt make any difference for my case-->
</head>
<body>
<div class="g-recaptcha"
      data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxx"
      data-callback="onSubmit"
      data-size="invisible">
</div>
<script>
    //Window.onload = setTimeout(function(){grecaptcha.execute()},2000) this works!
    Window.onload = grecaptcha.execute() //----this doesn't work---//

</script
</body>

您可以将参数设置为 url 定义 onload 回调:

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback">
</script>
<script>
function onloadCallback(){
  grecaptcha.execute();
 }
</script>

哦!!我刚刚使用

让它工作
$(window).on('load',function(){
    grecaptcha.execute()
})

感谢@jonasw 指出问题出在 window.onload 事件上 =D