0

I saw the code snippets at Google reCaptcha within SweetAlert modal window , particularly the one without the jquery (the 1st answer)

But that solution makes the captcha box visible.

How do i make it invisible within Sweetalert? I will do a server backend validation

I looked at https://github.com/prathameshsawant7/multiple-invisible-recaptcha and included the entire code from init_recaptcha.js along with the "onOpen" feature of SWAL... but no luck. The captcha is not set in the form.

Any help will be appreciated> I need the invisible captcha as I will triggering several SWAL forms within the HTML tag of the sweetalert (needed for multiple inputs at time)

<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <!-- Bootstrap CSS -->
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <link rel="stylesheet" href="css/cover.css">
  <script src="js/jquery1.11.1.min.js" type="text/javascript"></script>
  <script src="js/sweetalert2@10.js"></script>
  <script>
    $(document).ready(function() {
      $(document).on('click', '#comment_button', function(e) {
        e.preventDefault();
        //var M_user = "";
        Swal.fire({
          title: 'Add a comment to the page',
          titleText: 'Add a comment to the page',
          //included dynamically... :-)
          width: '75%',
          position: 'center',
          showCancelButton: true,
          showConfirmButton: false,
          showCloseButton: true;
          allowOutsideClick: false,
          focusConfirm: false,
          //grow: 'fullscreen',
          allowEscapeKey: true,
          html: '<div class="card"><form name="form2" id="form2" method="post" action="process3.php"><div class="form-group"><label for="InputText2">Enter Text (Recaptcha 2)</label><input type="text" class="form-control" id="text2" name="textmsg" placeholder="Enter random text" value="this_is_textmsg"></div><div class="form-group"><label for="InputText3">Enter Text :</label><input type="text" class="form-control" id="textv3" name="textmsg3" placeholder="Enter random text" value="this_is_textmsg3"></div><div id="recaptcha-form-2" style="display:none;"></div><input type="button" class="btn btn-primary" onclick="formSubmit(\'2\')" value="Submit" /></form></div>',
          footer: 'We reserve the right to moderate your comments if we feel the need.',
          onOpen: function() {
            console.log('setting initial values, if any on onOpen');

            /***
             * @Created by: Prathamesh Sawant (prathameshsandeepsawant@gmail.com)
             * @Date : 24/07/2017
             * @description To handle Multiple Google Invisible reCaptcha Implementation
             */

            /**************************************************************************\
             * Step 1 - Initialize reCaptcha Site Key and Widget eg: widget_1 for Form 1
             * Step 2 - In init function add code to create form submit callback action.
             * Step 3 - Call renderInvisibleReCaptcha function by passing reCaptcha ID 
             *          and createCallbackFn Response.
             ***************************************************************************/

            "use strict";

            var PS = PS || {};
            var widget_1;
            var widget_2;
            var widget_3;
            var recaptcha_site_key = 'my Real Site Key Goes here....removed for stackoverflow';

            if (typeof PS.RECAPTCHA === 'undefined') {
              (function(a, $) {
                var retryTime = 300;
                var x = {
                  init: function() {
                    if (typeof grecaptcha != 'undefined') {

                      //For Form 1 Initialization
                      if ($('#form1 #recaptcha-form-1').length > 0) {
                        var callbackFn = {
                          action: function() {
                            saveData('1'); //Here Callback Function
                          }
                        }
                        /*--- 'recaptcha-form-1' - reCaptcha div ID | 'form1' - Form ID ---*/

                        widget_1 = x.renderInvisibleReCaptcha('recaptcha-form-1', x.createCallbackFn(widget_1, 'form1', callbackFn));

                      }

                      //For Form 2 Initialization
                      if ($('#form2 #recaptcha-form-2').length > 0) {
                        var callbackFn = {
                          action: function() {
                            saveData('2'); //Here Callback Function
                          }
                        }
                        /*--- 'recaptcha-form-2' - reCaptcha div ID | 'form2' - Form ID ---*/
                        console.log('defining widget 2');
                        widget_2 = x.renderInvisibleReCaptcha('recaptcha-form-2', x.createCallbackFn(widget_2, 'form2', callbackFn));
                      }

                      //For Form 3 Initialization
                      if ($('#form3 #recaptcha-form-3').length > 0) {
                        var callbackFn = {
                          action: function() {
                            saveData('3'); //Here Callback Function
                          }
                        }
                        /*--- 'recaptcha-form-3' - reCaptcha div ID | 'form3' - Form ID ---*/
                        widget_3 = x.renderInvisibleReCaptcha('recaptcha-form-3', x.createCallbackFn(widget_3, 'form3', callbackFn));
                      }
                    } else {
                      setTimeout(function() {
                        x.init();
                      }, retryTime);
                    }
                  },
                  renderInvisibleReCaptcha: function(recaptchaID, callbackFunction) {
                    return grecaptcha.render(recaptchaID, {
                      'sitekey': recaptcha_site_key,
                      "theme": "light",
                      'size': 'invisible',
                      'badge': 'inline',
                      'callback': callbackFunction
                    });
                  },
                  createCallbackFn: function(widget, formID, callbackFn) {
                    return function(token) {
                      $('#' + formID + ' .g-recaptcha-response').val(token);
                      if ($.trim(token) == '') {
                        grecaptcha.reset(widget);
                      } else {
                        callbackFn.action();
                      }
                    }
                  }
                }
                a.RECAPTCHA = x;
              })(PS, $);
            }

            $(window).load(function() {
              PS.RECAPTCHA.init();
            });
          },
          preConfirm: function(login) {
            //run any stuff to do before login here
            console.log('doing before preConfirm  stuff....');
            //let s_user_name = Swal.getPopup().querySelector('#s_user_name').value;
            //M_user= s_user_name;
          },
        }).then(function(result) {
          console.log('then function result initial');

          if (result.value) {
            console.log('Doing if result.value here...');
          }
        }) //swal.fire end
      }); //function(e) ends
    }); //doc ready ends
  </script>
</head>

<body>
  <div class="site-wrapper">
    <div class="site-wrapper-inner">
      <div class="cover-container">
        <div class="masthead clearfix">
          <div class="inner">
            <center>
              <h3 class="">Handle Multiple Invisible Recaptcha</h3>
            </center>
          </div>
        </div>
        <div class="inner cover">
          <hr>
          <form id="comment_form" name="comment_form_name"><button id="comment_button" class="coach_button">Leave a Comment...</button></form>
          </hr>
          <div class="mastfoot">
            <div class="inner">
              <p>Sample template by @Prathamesh-Sawant to implement multiple invisible recaptcha on single page dynamically.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="js/popper.min.js"></script>
    <script src="js/bootstrap.min.js"></script>

    <script type="text/javascript" src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
    <script src="js/form.js" async defer></script>
</body>

</html>
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
Rajan
  • 137
  • 9

1 Answers1

0

I figured it out

Basically, inside sweetalert2, captcha doesn't render...

I was anyway using multiple fields in SWAL... so I had to use fields inside the HTML parameter.

To address the invisible captcha, I took an idea from Invisible reCaptcha AJAX Call . From within sweetalert, using Swal.getPopup().querySelector('#field').value, in pre-confirm, I will populate hidden fields in the form that is outside of sweetalert and submit it via Ajax

Not a brilliantly clean solution but, hey, it works!

Rajan
  • 137
  • 9