Docs

CAPTCHA widget in JavaScript forms

7 min readUpdated November 19, 2026

Some forms don’t exist when the page first loads: a login drawer, a modal, a form fetched over AJAX, or a form built by a script. Nahnu Login Shield can put its CAPTCHA widget into these forms too, with several widgets on one page at the same time. This topic shows the full flow and the browser-side window.NAHNLSWidget object.

For a normal server-rendered form, you don’t need any of this. See Protect any other form.

The idea#

  1. On the normal page load, make sure the widget script is on the page.
  2. When your code builds the form, ask PHP for the widget HTML in AJAX mode and add it to the form.
  3. After you insert the form into the page, call NAHNLSWidget.init() on it.
  4. Submit the whole form, including the widget’s hidden fields.
  5. Check the submission on the server with nahnls_check_submission().
  6. After a failed attempt, call NAHNLSWidget.reset() so the visitor can try again.

Step 1: Load the widget script on the page#

Make sure widget.js is on the page when it loads, even if the form isn’t there yet.

add_action( 'wp_enqueue_scripts', function () {
    if ( function_exists( 'nahnls_enqueue_widget_assets' ) ) {
        nahnls_enqueue_widget_assets();
    }
} );

This also passes the script the list of provider script addresses it needs. If the script isn’t on the page when the HTML arrives, there is nothing to start the widget.

Step 2: Get the widget HTML in AJAX mode#

$widget = nahnls_widget_html( [ 'form_id' => 'nav_login', 'context' => 'ajax' ] );

wp_send_json_success( [
    'html' => $form_html . wp_kses( $widget, nahnls_markup_allowed_html() ),
] );
ArgumentDefaultNotes
form_id'custom'Also the reCAPTCHA v3 action in ajax context. Characters other than A-Za-z0-9_/ become _
echofalseEchoes through wp_kses( …, nahnls_markup_allowed_html() )
context'page''ajax' makes markup for NAHNLSWidget.init()

In ajax context:

  • Third-party widgets come as .nahnls-captcha elements with data-provider, data-sitekey and data-config attributes. They do not carry the provider’s own class (.g-recaptcha, .h-captcha, .cf-turnstile), so the provider’s automatic start-up never claims them. NAHNLSWidget.init() starts them with each provider’s explicit API.
  • All the settings travel in the markup, so it works even when the HTML is made after the footer scripts were printed, or in an admin-ajax or REST response.
  • For security, provider script addresses are never read from the markup. They come only from the settings the plugin passed to the page. An ajaxUrl in the markup is accepted only when it is on the page’s own origin.
  • No <script> tag is ever returned. The page must already load widget.js (Step 1). If the provider’s script isn’t on the page yet, init() adds it.
  • Widget ids are unique per instance. The first widget on a page keeps #oopspam-ls-widget and #oopspam-ls-token. Later ones get -2, -3, and so on. HTML made after the page was printed gets a random suffix.
  • The hidden field names never change, so nahnls_check_submission() reads them as usual: nahnls_widget_token, nahnls_rc3_token, g-recaptcha-response, h-captcha-response, cf-turnstile-response, frc-captcha-solution, nahnls_js. The form nonce (nahnls_form_nonce) is part of the markup too.

Step 3: Start the widget#

After you insert the form into the page:

drawerBody.innerHTML = formHtml; // includes the widget HTML from Step 2
window.NAHNLSWidget.init( drawerBody );

Calling init() more than once is harmless, because each widget is marked data-initialized="1" after it starts.

Step 4: Submit everything#

Send all the form’s fields, including the hidden ones the widget added. With FormData, that happens automatically:

form.addEventListener('submit', function (e) {
    e.preventDefault();
    fetch(ajaxUrl, { method: 'POST', body: new FormData(form), credentials: 'same-origin' })
        .then(r => r.json())
        .then(handleResult);
});

With reCAPTCHA v3 and invisible Turnstile, the widget gets a fresh token when the form is submitted and then submits the form again with requestSubmit(). Your submit listener then sees the filled field. See “Per provider” below.

Step 5: Check it on the server#

$check = nahnls_check_submission( 'nav_login' );
if ( is_wp_error( $check ) ) {
    wp_send_json_error( [ 'message' => $check->get_error_message() ] );
}

Use the same form_id as in Step 2.

Step 6: Reset after a failed attempt#

window.NAHNLSWidget.reset( drawerBody );

Tokens from CAPTCHA providers can be used once. After a failed login, call reset() before the visitor retries.

The NAHNLSWidget object#

MethodReturnsWhat it does
NAHNLSWidget.init( container? )number of widgets startedStarts every widget that isn’t started yet inside container (an element, document, or a selector; default document). Also sets the nahnls_js hidden fields inside the container to 1
NAHNLSWidget.reset( container? )numberClears used tokens and resets every widget inside container
NAHNLSWidget.execute( container? )PromiseGets fresh reCAPTCHA v3 or invisible Turnstile tokens now. Only needed if you submit the form without a submit event
window._nahnlsWidgetInitAn older alias of NAHNLSWidget.init

What reset() does for each provider: the plugin’s own widget goes back to unchecked (and verifies again at once in auto-verify mode); grecaptcha.reset(id), hcaptcha.reset(id), turnstile.reset(id); Friendly Captcha’s WidgetInstance.reset(); reCAPTCHA v3 fields are emptied.

Per provider#

ProviderExplicit API usedOn submit
OOPSpam (the plugin’s own widget)Its own AJAX verificationHolds the submit until verified (manual mode asks for a click)
reCAPTCHA v2grecaptcha.render( el, { sitekey } )Nothing extra
reCAPTCHA v3grecaptcha.execute( sitekey, { action } )Fetches a fresh token into nahnls_rc3_token, then submits again
hCaptchahcaptcha.render( el, { sitekey } )Nothing extra
Turnstile (managed)turnstile.render( el, { sitekey, appearance: 'always' } )Nothing extra
Turnstile (invisible)turnstile.render( el, { sitekey, execution: 'execute', appearance: 'interaction-only' } )If there is no token, runs turnstile.execute() first, then submits again
Friendly Captchanew friendlyChallenge.WidgetInstance( el, { sitekey } )Nothing extra

The submit handler for reCAPTCHA v3 and invisible Turnstile is a listener on the form that runs in the capture phase. It runs before your own (bubble-phase) submit listeners and holds them back until the token is in place. Then it submits the form again with requestSubmit(), so an AJAX form’s own handler sees the filled field.

When the provider’s script isn’t loaded yet, init() queues the render, adds the script from the plugin’s address map (with render=explicit and an onload callback) unless a script for that provider is already on the page, and renders when the provider is ready.

Server-rendered and AJAX widgets together#

  • The automatic start on DOMContentLoaded only starts the plugin’s own widget and .nahnls-captcha elements. The providers’ own elements (.g-recaptcha and the like) are left to the provider’s own automatic start.
  • When you call init( container ) yourself, provider elements inside it that the provider has not drawn yet (no iframe, response field or instance) are drawn explicitly too. This check is repeated just before drawing, so a widget the provider already drew is never drawn twice.
  • On server-rendered pages, the scripts for reCAPTCHA v3 and invisible Turnstile keep handling the forms that were on the page at load. init() adds submit handling only to ajax-context v3 inputs, so a form is never hooked twice.
  • reset() on a classic reCAPTCHA v2 widget that init() did not draw finds the widget through its g-recaptcha-response field.

A complete example#

// 1. Page load.
add_action( 'wp_enqueue_scripts', function () {
    if ( function_exists( 'nahnls_enqueue_widget_assets' ) ) {
        nahnls_enqueue_widget_assets();
    }
} );

// 2. AJAX handler that returns the drawer form.
add_action( 'wp_ajax_nopriv_my_drawer_form', function () {
    $form = '<form id="drawer-login"><input name="log"><input type="password" name="pwd">'
          . '<button type="submit">Log in</button></form>';
    $widget = nahnls_widget_html( [ 'form_id' => 'nav_login', 'context' => 'ajax' ] );
    $form = str_replace( '<button', wp_kses( $widget, nahnls_markup_allowed_html() ) . '<button', $form );
    wp_send_json_success( [ 'html' => $form ] );
} );

// 5. AJAX handler that receives the login.
add_action( 'wp_ajax_nopriv_my_drawer_login', function () {
    $check = nahnls_check_submission( 'nav_login' );
    if ( is_wp_error( $check ) ) {
        wp_send_json_error( [ 'message' => $check->get_error_message() ] );
    }
    // Continue with the login...
} );
Code
// 1. Page load.
add_action( 'wp_enqueue_scripts', function () {
    if ( function_exists( 'nahnls_enqueue_widget_assets' ) ) {
        nahnls_enqueue_widget_assets();
    }
} );

// 2. AJAX handler that returns the drawer form.
add_action( 'wp_ajax_nopriv_my_drawer_form', function () {
    $form = '<form id="drawer-login"><input name="log"><input type="password" name="pwd">'
          . '<button type="submit">Log in</button></form>';
    $widget = nahnls_widget_html( [ 'form_id' => 'nav_login', 'context' => 'ajax' ] );
    $form = str_replace( '<button', wp_kses( $widget, nahnls_markup_allowed_html() ) . '<button', $form );
    wp_send_json_success( [ 'html' => $form ] );
} );

// 5. AJAX handler that receives the login.
add_action( 'wp_ajax_nopriv_my_drawer_login', function () {
    $check = nahnls_check_submission( 'nav_login' );
    if ( is_wp_error( $check ) ) {
        wp_send_json_error( [ 'message' => $check->get_error_message() ] );
    }
    // Continue with the login...
} );
// 3. Show the form and start the widget.
fetch(ajaxUrl + '?action=my_drawer_form')
    .then(r => r.json())
    .then(({ data }) => {
        drawerBody.innerHTML = data.html;
        window.NAHNLSWidget.init(drawerBody);
        const form = drawerBody.querySelector('#drawer-login');
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            const body = new FormData(form);
            body.append('action', 'my_drawer_login');
            fetch(ajaxUrl, { method: 'POST', body })
                .then(r => r.json())
                .then((res) => {
                    if (!res.success) {
                        showError(res.data.message);
                        window.NAHNLSWidget.reset(drawerBody); // 6. Reset after failure.
                    }
                });
        });
    });
Code
// 3. Show the form and start the widget.
fetch(ajaxUrl + '?action=my_drawer_form')
    .then(r => r.json())
    .then(({ data }) => {
        drawerBody.innerHTML = data.html;
        window.NAHNLSWidget.init(drawerBody);
        const form = drawerBody.querySelector('#drawer-login');
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            const body = new FormData(form);
            body.append('action', 'my_drawer_login');
            fetch(ajaxUrl, { method: 'POST', body })
                .then(r => r.json())
                .then((res) => {
                    if (!res.success) {
                        showError(res.data.message);
                        window.NAHNLSWidget.reset(drawerBody); // 6. Reset after failure.
                    }
                });
        });
    });

Limitations#

  • Only the providers selectable on the Widget tab are supported. For any other value, nahnls_widget_html() returns only the hidden fields (form nonce and JavaScript marker), with no widget.
  • If the page can be cached for a long time, see Caching and login pages. The form nonce in the markup has to be fresh when the visitor submits. Pages with forms built by AJAX get a fresh nonce with each request, which avoids that problem.
  • If widget.js is blocked or delayed by an optimization plugin, nothing starts. See Caching and login pages.

Was this helpful?

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only