No CAPTCHA reCAPTCHA Resizing

前端 未结 14 1992
故里飘歌
故里飘歌 2020-12-14 01:23

Hi I just added Google\'s No CAPTCHA reCAPTCHA to my website, and I am running into a small little issue. It does NOT fit on my mobile website, and that is

相关标签:
14条回答
  • 2020-12-14 02:12

    If you don't like the CSS solution, you may try the JS.

    The idea is to dynamically switch between compact and normal mode of the recaptcha plugin.

    I will provide an example with jQuery onboard, but it shouldn't be much to port it to pure JS.

    I assume you have following HTML code on the site.

    <div>
        <div class="g-recaptcha" data-sitekey="[your-key-here]"></div>
    </div>
    

    Firstly you need to load gRecaptcha 2 explicitly and provide onload callback:

    <script type='text/javascript' src='https://www.google.com/recaptcha/api.js?hl=en&#038;onload=recaptchaCallback&#038;render=explicit'>
    

    Next, create your callback function which will also be your javascript media query.

    function recaptchaCallback()
    {
        var mq = window.matchMedia("(max-width: 400px)");
        mq.addListener(recaptchaRenderer);
        recaptchaRenderer(mq);
    }
    

    The last thing is to render the recaptcha widget.

    function recaptchaRenderer(mq)
    {
        var recaptcha = $('.g-recaptcha').eq(0);
        var data = recaptcha.data();
        var parent = recaptcha.parent();
    
        recaptcha.empty().remove();
    
        var recaptchaClone = recaptcha.clone();
        parent.append(recaptchaClone);
        recaptchaClone.data(data);
    
        var options = {
            'sitekey': data['sitekey'],
            'size': 'compact'
        };
        if(!mq.matches)
        {
            options['size'] = 'normal';
        }
        grecaptcha.render(recaptchaClone.get(0), options);
    }
    

    You may wonder why I empty the div and clone all the g-recaptcha content. It's because gRecaptcha 2 wouldn't let you render second time to the same element. There could be a better way, but it's all I found for now.

    0 讨论(0)
  • 2020-12-14 02:13

    According to the documentation from Google shows a data-size attribute which can be set and this worked for me.

     <div class="g-recaptcha" data-sitekey="XXXXXXXX" data-size="compact"></div>
    

    But, the answer from @GeekGoddess provides a little more flexibility in sizing.

    0 讨论(0)
提交回复
热议问题