0

We have the Google reCAPTCHA all set up and working (in other uses in our org), but I'm having trouble getting it to work on my VF page.
Clicking the submit button fires the recaptcha and I get a token, but the controller function is never called.
I suspect that this might be because as Google says here:

Note: your onload callback function must be defined before the reCAPTCHA API loads. To ensure there are no race conditions:

  • order your scripts with the callback first, and then reCAPTCHA
  • use the async and defer parameters in the script tags

Visualforce will not let me use async and defer in the script tags, so I don't. That seems to work anyway (since I get a token).
I'm guessing that when the recaptcha api loads, the last line in the callback function is empty, and so it is never called.

So how can I can a server side function once the recaptcha is verified?

Controller:

public String recaptchaPublicKey {get;set;}
public String recaptchaToken {get; set;}

public void controllerFunction(){
    System.debug('Controller function called!');
    Systemd.debug(recaptchaToken);
}

Visualforce:

<head>
    <script type="text/javascript">
        var onSubmit = function(token) {
            console.log('success!');
            console.log(token);
            callControllerFunction(token);
        };

        var recaptchaOnloadCallback = function() {
          grecaptcha.render('submit', {
            'sitekey' : '{!recaptchaPublicKey}',
            'callback' : onSubmit
          });
        };

    </script>
</head>
<body>
    <apex:form >
        <apex:actionFunction name="callControllerFunction" action="{!controllerFunction}">
            <apex:param name="recaptchaTokenParam" value="" assignTo="{!recaptchaToken}"/>
        </apex:actionFunction>
        <input id='submit' type="submit" value="Submit"/>
    </apex:form>
    <script src="https://www.google.com/recaptcha/api.js?onload=recaptchaOnloadCallback" ></script>
0

So it turns out that it wasn't the Google thing.
Instead I had some kind of race condition due to the button's id being submit. (I was eventually able to get a coherent JS error that helped me track this down).
Changing the button's id to submitButton resolved that issue and the reCAPTCHA script was able to run.

Important note: the code I was using which included button with the bad id, was lifted directly from Google's sample code in the above link (in the question). So I don't know if this is a Visualforce conflict or a browser thing or a new version of the reCAPTCHA script. But whatever it is, the sample code from Google doesn't run as-is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.