项目中recaptcha__en.js多次调用问题排查:测试reCAPTCHA示例代码
It sounds like you're hitting repeated requests for the reCAPTCHA script (recaptcha__en.js) when rendering multiple widgets, which is almost always caused by loading the core reCAPTCHA script more than once in your page. Let’s break down the issue and fix it properly:
Root Cause
The reCAPTCHA script only needs to be loaded once per page load. If you’re including the script tag multiple times (e.g., in separate components, or dynamically adding it each time you call grecaptcha.render()), each inclusion triggers a new request for recaptcha__en.js.
Correct Implementation
Here’s how to render multiple widgets without duplicate script requests:
Load the reCAPTCHA script once (place this at the bottom of your HTML body, or in the
<head>withasync/defer):<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>This loads the script a single time and triggers your
onloadCallbackonce it’s ready to use.Render all widgets in the single onload callback:
Use your existing callback to render both widgets—this leverages the already loaded script instance instead of requesting it again:var onloadCallback = function() { // Render first widget var widgetId1 = grecaptcha.render('html_element', { 'sitekey': 'My-Site-Key' }); // Render second widget var widgetId2 = grecaptcha.render('html_element2', { 'sitekey': 'My-Site-Key' }); };Update your form to use widget-specific responses:
When verifying submissions, reference the correct widget ID withgrecaptcha.getResponse()to get the right token for each widget:<form action="javascript:alert(grecaptcha.getResponse(widgetId1) + ' | ' + grecaptcha.getResponse(widgetId2))" method="post"> <div id="html_element"></div> <div id="html_element2"></div> <input type="submit" value="Submit"> </form>
Additional Checks
- Eliminate duplicate script tags: Scan your codebase to ensure you’re not including the reCAPTCHA script in multiple places (e.g., a header template and a component template).
- Guard against dynamic script duplicates: If you’re adding the script via JavaScript, add a check to avoid re-inserting it:
if (!document.querySelector('script[src*="recaptcha/api.js"]')) { const script = document.createElement('script'); script.src = 'https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit'; script.async = true; script.defer = true; document.body.appendChild(script); }
By following this approach, you’ll only load recaptcha__en.js once, even when rendering multiple reCAPTCHA widgets.
内容的提问来源于stack exchange,提问作者Rueff19

