如何通过JavaScript阻止Google Chrome文本框建议与密码保存
解决Chrome密码管理器保存及自动填充问题
方法一:直接用原生属性禁用密码保存与自动填充(推荐)
不用折腾修改输入框type,直接给密码框添加autocomplete相关属性,就能让Chrome放弃保存和填充密码,同时避免地址填充问题:
<!-- 直接在HTML中给密码框添加属性 --> <input id="UserPassword" type="password" autocomplete="new-password" readonly onfocus="this.removeAttribute('readonly')">
或者用jQuery在页面就绪时设置:
$(document).ready(function() { $("#UserPassword") .attr("autocomplete", "new-password") .attr("readonly", true) .on("focus", function() { $(this).removeAttr("readonly"); }); });
autocomplete="new-password":明确告知Chrome这是新密码输入框,不要保存或填充已有密码readonly+ 聚焦移除:针对部分Chrome版本忽略autocomplete属性的情况,通过只读状态阻止自动填充,聚焦后恢复可编辑
方法二:保留原type修改方案,同时禁用地址填充
如果一定要坚持把Chrome下的密码框改成text类型,需要额外添加属性阻止地址自动填充:
$(document).ready(function() { var isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor); if (isChrome) { $("#UserPassword") .attr("type", "text") .attr("style", "-webkit-text-security:disc;") .attr("autocomplete", "off") .attr("readonly", true) .on("focus", function() { $(this).removeAttr("readonly"); }); } else { $("#UserPassword") .attr("type", "password") .attr("autocomplete", "new-password"); } });
补充说明
- 不要仅依赖
autocomplete="off":部分Chrome版本会忽略该值,搭配new-password或readonly技巧更可靠 - 地址填充触发原因:当输入框被改为
text类型后,Chrome会将其识别为普通文本输入框,匹配地址自动填充规则,添加autocomplete属性可明确告知浏览器不要处理该输入框
内容的提问来源于stack exchange,提问作者umasankar
相关产品推荐
相关产品推荐

