Prevent submission of form until recaptcha3 g-recaptcha-response value is obtained

SEO has a significant impact on site load speed nowadays. Adding Google reCAPTCHA3 can reduce site speed by 35-40% in Google Lighthouse results. To combat this, I chose to load the reCAPTCHA3 library only when the user clicks or fills out a form field. I implemented this code successfully.


HTML Form Field

  <div class="control is-loading">
      <input name="instauser" id="author" class="input is-rounded is-focused is-medium" type="text" placeholder="https://instagram.com/p/41SW_pmmq4/">
   </div>
   <input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response" value="">
   <div class="control has-text-centered"><br>
      <button id="Button" type="submit" class="button is-danger is-active is-medium">Download &nbsp
      <img src="{{ asset('svg/downloads.svg') }}" width="25px"
         alt="Instagram video download" />
      </button>
   </div>
</form>

Javascript Code

<script type="text/javascript">

var reCaptchaFocus = function() {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.google.com/recaptcha/api.js?render=6LdvEswUAAAAADNVG2ng4ZIfA4mfKUJiuLmLgnUy';
head.appendChild(script);

var recaptchaInterval = setInterval(function() {
if( !window.grecaptcha || !window.grecaptcha.execute ) { return; }

clearInterval( recaptchaInterval );

grecaptcha.execute('6LdvEswUAAAAADNVG2ng4ZIfA4mfKUJiuLmLgnUy', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
});
}, 100 );
    document.getElementById('author').removeEventListener('focus', reCaptchaFocus);
    };
    document.getElementById('author').addEventListener('focus', reCaptchaFocus, false);
</script>

However, a new issue has arisen where slow internet connections result in a delay in loading the hidden g-recaptcha-response input value. This delay sometimes leads to users submitting the form before the value is loaded, causing errors. To prevent this, I want to disable the submit button until the g-recaptcha-response value is filled in the hidden input type. You can test this on the website

I could really use some assistance.

Answer №1

Here is the solution to my inquiry

<script type="text/javascript">
var reCaptchaFocus = function() {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://www.google.com/recaptcha/api.js?render=6LdvEswUAAAAADNVG2ng4ZIfA4mfKUJiuLmLgnUy';
head.appendChild(script);
document.getElementById("Button").disabled = true;

var recaptchaInterval = setInterval(function() {
if( !window.grecaptcha || !window.grecaptcha.execute ) { return; }

clearInterval( recaptchaInterval );

grecaptcha.execute('6LdvEswUAAAAADNVG2ng4ZIfA4mfKUJiuLmLgnUy', {action: 'homepage'}).then(function(token) {
document.getElementById('g-recaptcha-response').value=token;
document.getElementById("Button").disabled = false;
//document.querySelector('button[type="submit"]').setAttribute('disabled', '');
});
}, 100 );
    document.getElementById('author').removeEventListener('focus', reCaptchaFocus);
    };
    document.getElementById('author').addEventListener('focus', reCaptchaFocus, false);
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in canvas-sketch: "THREE.ParametricGeometry has been relocated to /examples/jsm/geometries/ParametricGeometry.js"

I recently started using canvas-sketch to create some exciting Three.js content. For my Three.js template, I utilized the following command: canvas-sketch --new --template=three --open The version that got installed is 1.11.14 canvas-sketch -v When atte ...

The JavaScript animations in AngularJS using ng-class are not being activated

I've been attempting to apply js-defined animations to the ng-class directive using the standard syntax of add and remove, but for some reason, the animations are not running. After checking the logs, it seems that the add and remove functions are not ...

I am attempting to display only the description of the button that I click on

How can I ensure that only the container pressed will display its description when the description button is clicked, instead of all mapped containers showing their descriptions? `import { useState } from "react"; export default function Se ...

Display drop-down item when selected for the first time and hide it when selected for the same item for the second time

Is there a way to display form input when "C" is selected and hide it when "A", "B", or "D" are selected? If "C" is selected again after initially showing the form input, should it be hidden? For example, if "C" is selected for the first time, the form inp ...

Is relying on jQuery to submit a form without the use of PHP secure?

My website has a user account creation form with a "submit" button that is actually an html type='button', not a true submit button. When this button is clicked, I rely on jQuery to call ('#form').submit(); in order to submit the form. ...

What's the best way to enable touch scrolling for items within a div container?

I am in the process of creating a code snippet that will allow users to scroll through items within a div, similar to a spinning wheel or slot machine. While I am aware of an existing solution for iPhone and iPod, I want to develop a simpler, more streamli ...

encountering difficulties with parsing JSON data within JQuery script on Laravel 5.2

In my Laravel project, I am attempting to dynamically populate a second dropdown menu based on the value selected in the first dropdown. This process involves using AJAX to update the options available in the second dropdown when a Cinema Hall is selected. ...

Having trouble extracting information from JSON object array following an AJAX post?

My website transfers data through JSON objects using Angular's $http post. If you'd like to see the console logs and responses, visit my website: Initially, I used x-form-urlencoded encoding successfully and decided to switch to application/jso ...

What can be done to ensure smooth functionality of my nested navigation menu on mobile devices?

I'm utilizing the incredible features of Base Web for my website. One of the components I am using is a menu with a child menu, based on this example. The menu works perfectly fine on desktop - when I hover over an option, the child menu appears. Howe ...

Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals ...

create a recurring design wallpaper within the TinyMCE editor

One of my functions alters the background of the tinymce editor. However, I am interested in having a wallpaper repeat in a similar fashion to background-repeat: repeat; in CSS. How can I achieve this? Here is the function: function SettinymceImage(bg_i ...

What is the reason for innerHTML not functioning properly when trying to include HTML?

Apologies for my poor English, but I am determined to solve this issue using HTML code. <body> <div id="booklist"> <?php include("../templates/nav.php"); ?> <div class="hero"> <?php include("../templates/aside.ph ...

JavaScript for validating forms in PHP

Hey everyone, I'm struggling to understand why the alert box isn't showing up when I run this code. I'm new to programming and find HTML easy, but I'm currently in a PHP class where we have been tasked with creating and validating a for ...

Unable to dynamically populate Bootstrap select with real-time search and multiple options using jQuery

How can I dynamically populate a select statement with options retrieved from PHP code? <select name='friends[]' id='friends' class='selectpicker show-tick form-control' data-live- search='true' multiple& ...

Inspect the key within a complex hierarchy of nested objects in an array

I am working with an array of nested objects and need to extract the value of a specific key property. Currently, I am using a for loop and checking for the existence of children property, but I feel there might be a more optimal way to accomplish this tas ...

Merging multiple observables with RxJs forkJoin

UPDATE : I'm currently facing a challenging issue that I can't seem to resolve. Within my code, there is a list of objects where I need to execute 3 requests sequentially for each object, but these requests can run in parallel for different obje ...

Issue with SideNav function in MaterializeCss following recent update

After updating the css/js files of the Materializecss design in my project from v0.97.5 to v0.97.8, I noticed that my SideNav isn't functioning correctly anymore. When I try to click on the menu, it slides out but the dark overlay covers the entire sc ...

Effective Ways to Redirect During or After Executing the onClick Function of Button

I am currently working on implementing a feature for my Next.js website. The functionality involves allowing users to create a new group by clicking a button, and then being redirected to an "Invite members" page with the auto-generated group_id included i ...

Error: $controller does not function as a controller within another controller

I recently started learning Angular JS and attempted to call one controller within another, but encountered the following error: ionic.bundle.js:21157 TypeError: $controller is not a function at new <anonymous> (http://localhost:8080/itravel/www/js/ ...

Tips for resolving the problem of Google Maps repeatedly appearing when utilizing the Auto-Loading feature

I need help understanding the issue that arose when loading the Google Maps API. "You have included the Google Maps API multiple times on this page. This may cause unexpected errors." This error occurred while attempting to automatically load the API. B ...