Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

noCAPTCHA reCAPTCHA disappearing in UpdatePanel

I'm implementing noCAPTCHA reCAPTCHA into an existing form with VB.Net. It is located within an UpdatePanel and uses server side validation to verify the user has completed the CAPTCHA (See Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server side)

If a user fails to the CAPTCHA or any other of the validated fields, the CAPTCHA fails to reload due to postback. How do resolve this and make it so that the CAPTCHA does not disappear after a postback?

My CAPTCHA code:

<div id="captcha" class="g-recaptcha" runat="server" data-sitekey="MySiteKey"></div>

The api.js is placed in the Site.Master header.

<script src="https://www.google.com/recaptcha/api.js" async defer></script>

To expand.

I have tried a work around but ultimately failed. I added

<div id="captcha" class="g-recaptcha" runat="server" data-sitekey="MySiteKey"></div>

to the body of my MasterPage and threw it in an UpdatePanel, gave it an id, etc.

    <asp:UpdatePanel UpdateMode="Conditional" runat="server" ID="noCaptcha">
        <ContentTemplate>
            <asp:ScriptManager runat="server"></asp:ScriptManager>
            <script src="https://www.google.com/recaptcha/api.js" async defer></script>
        </ContentTemplate>
    </asp:UpdatePanel>

I then created a function in the code-behind of the Site Master as follows:

Public Sub TriggerCaptchaReload()
    noCaptcha.Update()
End Sub

When the user tried to verify and submit the form

If they failed I attempted to cause the update panel to refresh with

CType(Me.Page.Master, MasterPage).TriggerCaptchaReload()

which is located on the control code behind.

This didn't work. Maybe there is a potential solution to find with that?

like image 906
Benjamin Avatar asked Dec 03 '22 17:12

Benjamin


1 Answers

To solve this issue I did the following:

My CAPTCHA code changed to the following div:

<div id="recaptcha" class="recaptcha"></div>

I then proceeded to implement explicit rendering on the reCAPTCHA by changing the api link to the following and placing it below the div above.

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

In the header of the page I included

<script type="text/javascript">
    var onloadCallback = function () {
        grecaptcha.render('recaptcha', {
            'sitekey': 'MySiteKey'
        });
    };
</script>

In the code behind if the CAPTCHA fails I reload the CAPTCHA with

ScriptManager.RegisterStartupScript(UpdatePanel1, UpdatePanel1.GetType(), "loadCaptcha", "grecaptcha.render('recaptcha', {'sitekey': 'MySiteKey' });", True)
like image 192
Benjamin Avatar answered Dec 15 '22 23:12

Benjamin