首页 文章

有没有办法在recaptcha 2中设置tabindex?

提问于
浏览
4

我有一个带有几个文本字段的自定义表单 . 所有这些元素都设置了 tabindex 值 . 但是一旦我放置了新的recaptcha就无法访问该复选框,因为它将tabindex设置为默认值0.有没有办法为新的验证码复选框设置选项卡索引?

以下代码演示了此问题:

<script src="https://www.google.com/recaptcha/api.js"></script>
<form action="" method="POST">
    <input type="text" name="username" tabindex="1" autofocus>
    <input type="password" name="password" tabindex="2">
    <div class="g-recaptcha" data-sitekey="[SITE KEY]"></div>
    <input type="submit" value="Login" tabindex="4">
</form>

注意 <script> 来自 <head> .

在表格中进行选项卡时,顺序如下:

  • 用户名

  • 密码

  • 提交按钮

  • 验证码

所需的顺序如下:

  • 用户名

  • 密码

  • 验证码

  • 提交按钮

2 回答

  • 3

    我昨天花了相当多的时间调试reCAPTCHA 2 API,寻找未记录的功能,而且我有理由相信Google没有提供API来执行此操作 .

    但是,您需要做的就是在生成的 iframe 元素上设置 tabindex 属性 . Google默认将其设置为 0 ,但我们没有理由无法更改它 . iframe 不会立即生成,因此您需要等待它首先渲染 .

    另外,如果我们可以在 .g-recaptcha 元素的 .g-recaptcha 元素中指定 tabindex ,那就太好了 .

    这是一个很好的小片段,它会循环 .g-recaptcha ,为 load 事件添加 iframe 的事件监听器(使用捕获阶段,因为事件不会冒泡),并将 iframetabIndex 属性设置为 data-attribute 属性的值 . 只需在您网页的页脚中包含此脚本,或在文档准备就绪时运行它 .

    //Loop over the .g-recaptcha wrapper elements.
    Array.prototype.forEach.call(document.getElementsByClassName('g-recaptcha'), function(element) {
        //Add a load event listener to each wrapper, using capture.
        element.addEventListener('load', function(e) {
            //Get the data-tabindex attribute value from the wrapper.
            var tabindex = e.currentTarget.getAttribute('data-tabindex');
            //Check if the attribute is set.
            if (tabindex) {
                //Set the tabIndex on the iframe.
                e.target.tabIndex = tabindex;
            }
        }, true);
    });
    

    在HTML中,包含所需的 data-tabindex 值 .

    <div class="g-recaptcha" data-sitekey="[SITE KEY]" data-tabindex="3">
    
  • 4

    在新版本的recaptcha中,您可以使用data-tabindex . https://developers.google.com/recaptcha/docs/display#render_param这样的事情:

    <div class="g-recaptcha" data-sitekey="[SITE KEY]" data-tabindex="[Custom tabindex]"></div>
    

    或者这个:

    <form action="" method="POST">
        <input type="text" name="username" tabindex="1" autofocus>
        <input type="password" name="password" tabindex="2">
        <div class="g-recaptcha"></div>
        <input type="submit" value="Login" tabindex="4">
    </form>
    <script src="https://www.google.com/recaptcha/api.js"></script>
    <script>
        var onloadCallback = function() {
            grecaptcha.render(document.querySelector(".g-recaptcha"), {
                'sitekey' : 'your site key',
                'tabindex' : 'custom tabindex',
            });
        };
    </script>
    

相关问题