问题
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?
回答1:
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 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)
回答2:
This solved my problems with recaptcha in update panels. Use pageLoad function with a loop with elements of the same class name then render with your secret key.
function pageLoad(sender, args) { $('.g-recaptcha').each(function (index, obj) { grecaptcha.render(obj, { 'sitekey': 'XXXXXXXXXXXX-XX' }); }); }
来源:https://stackoverflow.com/questions/30260259/nocaptcha-recaptcha-disappearing-in-updatepanel