iOS端Chrome中2FA短信验证码自动填充故障咨询
移动端Chrome多输入框2FA验证码自动填充问题解决方案
我之前刚好碰到过和你一模一样的问题——Safari里多独立输入框的OTP自动填充完美拆分到每个框,但移动端Chrome只会把整个验证码塞到第一个输入框。结合我当时的排查和解决经验,给你梳理下Chrome的逻辑和可行的方案:
Chrome OTP自动填充的核心逻辑
Chrome对autocomplete="one-time-password"的支持更偏向单输入框场景:当检测到短信中的验证码时,它只会把完整的验证码字符串注入到第一个匹配该属性的输入框中,不会自动拆分到多个输入框。而Safari则针对多输入框场景做了特殊处理,会自动拆分并触发每个框的change事件,这就是两者表现差异的原因。
具体解决方案
方案1:监听第一个输入框的输入事件,手动拆分填充
这是最通用的方案,不管Chrome的填充逻辑如何,我们主动处理第一个框的内容,拆分到其他输入框:
<!-- 输入框结构示例,第一个框保留OTP autocomplete,其他设为off --> <input type="tel" class="otp-input" autocomplete="one-time-password" maxlength="1"> <input type="tel" class="otp-input" autocomplete="off" maxlength="1"> <input type="tel" class="otp-input" autocomplete="off" maxlength="1"> <input type="tel" class="otp-input" autocomplete="off" maxlength="1"> <input type="tel" class="otp-input" autocomplete="off" maxlength="1"> <input type="tel" class="otp-input" autocomplete="off" maxlength="1">
const otpInputs = document.querySelectorAll('.otp-input'); const firstInput = otpInputs[0]; // 监听第一个输入框的输入事件 firstInput.addEventListener('input', (e) => { const fullCode = e.target.value.trim(); // 确保验证码长度和输入框数量一致 if (fullCode.length === otpInputs.length) { // 拆分验证码到每个输入框 otpInputs.forEach((input, index) => { input.value = fullCode[index]; // 手动触发change事件,和Safari的行为对齐 input.dispatchEvent(new Event('change')); }); // 聚焦到最后一个输入框,提升用户体验 otpInputs[otpInputs.length - 1].focus(); } }); // 额外处理用户手动输入的情况(可选) otpInputs.forEach((input, index) => { input.addEventListener('input', () => { // 如果当前输入框有内容,自动聚焦到下一个 if (input.value && index < otpInputs.length - 1) { otpInputs[index + 1].focus(); } }); });
方案2:监听安卓Chrome的smsreceived事件(主动获取验证码)
部分安卓版本的Chrome支持smsreceived事件,可以直接捕获短信内容,无需等待用户点击自动填充:
window.addEventListener('smsreceived', (e) => { const smsContent = e.data; // 提取6位数字验证码(根据你的验证码格式调整正则) const codeMatch = smsContent.match(/\d{6}/); if (codeMatch) { const otpCode = codeMatch[0]; otpInputs.forEach((input, index) => { input.value = otpCode[index]; input.dispatchEvent(new Event('change')); }); } });
注意事项
- 输入框建议用
type="tel",这样移动端会弹出数字键盘,更符合验证码输入场景; - 每个输入框必须设置
maxlength="1",避免用户输入多个字符; - 测试时需要用真实的短信推送,Chrome的OTP自动填充在本地模拟环境可能不会触发;
- 如果你的验证码长度不是6位,记得调整代码中的长度判断和正则表达式。
内容的提问来源于stack exchange,提问作者Pablo88
相关产品推荐
相关产品推荐

