ide*_*chi 3 javascript forms recaptcha
您好,这是我第一次尝试在这里发布问题。
我想知道是否可以从g-recaptcha 标签中获取 widgetId,而不是从reCAPTCHA v2 的grecaptcha.render()的返回值中获取 widgetId。
这背后的原因是我有 2 个不同的脚本来处理同一页面上的每 2 个表单。我希望能够单独重置 reCAPTCHA。
每个脚本都有自己的 onload 回调,应该获取自己的 widgetId。但这不起作用,因为似乎只有 1 个 onload 回调函数可以通过 google reCAPTCHA 代码的 url 参数调用。
我无法将多个 onload 回调函数设置为 recaptcha 源 url,如下所示。
“ https://www.google.com/recaptcha/api.js?onload=onloadCallback1,onloadCallback2 &render=onload”
“ https://www.google.com/recaptcha/api.js?onload[]=onloadCallback1&onload[]=onloadCallback2 &render=onload”
所以我想也许我可以在加载后从 g-recaptcha 标签获取小部件 ID...
有什么想法或解决方案吗???
嗯,,,这并不复杂,但我想出了一个根据 g-recapctha 类的顺序获取小部件 id 的想法。该函数接受目标 recaptcha 框的 id 作为参数,并返回与之关联的 g-recaptcha 类的索引。
// recaptha box 1
<div id="recaptchaBox-1" class="g-recaptcha" data-sitekey="xxx"></div>
<input id="resetBtn1" type="button" value="Reset1">
// recaptha box 2
<div id="recaptchaBox-2" class="g-recaptcha" data-sitekey="xxx"></div>
<input id="resetBtn2" type="button" value="Reset2">
/**
* Returns widgetId from a given element id
* @param {string} elementId
* @return {number} i
*/
function getWidgetId(elementId) {
const recaptchaBoxes = document.querySelectorAll('.g-recaptcha');
const targetBox = document.querySelector(`#${elementId}`);
for (let i = 0; i < recaptchaBoxes.length; i++) {
if (recaptchaBoxes[i].id === targetBox.id) {
return i;
}
}
}
// Get the widgetId for each boxes.
const widgetId1 = getWidgetId('recaptchaBox-1');
const widgetId2 = getWidgetId('recaptchaBox-2');
// Assign grecaptcha.reset() for each buttons on click event.
document.getElementById('resetBtn-1').addEventListener('click', () => grecaptcha.reset(widgetId1));
document.getElementById('resetBtn-2').addEventListener('click', () => grecaptcha.reset(widgetId2));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3256 次 |
| 最近记录: |