Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New Google reCAPTCHA JavaScript namespace callback

We're trying to implement the new Google reCAPTCHA on our website, however when we try and load a callback from it using a namespaced function, the callback does not run.

Changing the callback to not use a callback works correctly. We're doing something similar with the Google Maps API, which works fine.

Is there any way to get around this, or is this a limitation of the new Google reCAPTCHA system?

Code

<script>
    var namespace = {};
    namespace.captcha = function() {
        alert("Hello world!")
    };
</script>
<script src="//www.google.com/recaptcha/api.js?onload=namespace.captcha&render=explicit" async defer></script>

The issue really is that we want to keep all our code wrapped up in namespaced scripts using revealing modular pattern. A way around this is to create a global variable and use this as the callback, but it's not quit what I had hoped for.

Global callback

<script>
    var namespace = {};
    namespace.captcha = (function() {         
        function call() {
            alert("Hello world!")
       };
       window.callback = namespace.captcha.call;   
       return call:call;
    })();
</script>
<script src="//www.google.com/recaptcha/api.js?onload=callback&render=explicit" async defer></script>
like image 735
Toby Avatar asked Jan 05 '15 09:01

Toby


1 Answers

You can do it by using the Javascript API to set the callback.

This will allow you to use the namespaced callback, or even the scope protected callback when using a framework.

I couldn't test it, so as an example:

var script = document.createElement('script');

script.id = 'container'
script.src = '//www.google.com/recaptcha/api.js?render=explicit';
script.async = true;
script.defer = true;

script.onload = () => { ... };

document.body.appendChild(script);

For the V3

Your script.onload function could be like:

grecaptcha.ready(function() {
  namespace.captcha();
});

For the V2

Your script.onload function could be like:

grecaptcha.render('container', { 
  callback: namespace.captcha
});
like image 178
Gatsbimantico Avatar answered Oct 13 '22 04:10

Gatsbimantico