'autocomplete="off"'在Chrome中不起作用解决方案

最近项目中遇到一个令人头疼的问题,查阅各种资料,尝试各种方法,最终得以解决;哎···下面就说说这心酸的历程吧。

大家都知道autocomplete属性是表单字段中的HTML5新属性,该属性有两种状态值,分别为"on" 和 "off",该属性可省略:省略属性值后默认值为"on",也可以省略属性名,直接写入关键字on或off。

网站项目中,有登录和注册的弹框,在除chrome的浏览器中一切都ok,一旦在谷歌浏览器中,问题来了:
首先从登录弹框中登陆成功,chrome会弹出是否保存密码的提示框,点击保存密码按钮,


然后接着退出账户,
这时打开注册弹框,你会发现注册弹框中用户名和密码也被默认填写进去了(登录弹框中默认填写进去符合逻辑),


这现象就诡异了,开始各种查,cookie,本地缓存,等等,都解决不了这问题;

查阅后,很多没有这个的解决方案。


1  通常我们会在form表单上加入autocomplete="off" 或者 在输入框中加入autocomplete="off"

<form method="post" action="" name="login" autocomplete="off">

</form>
//或者
<input id="name" type="text" name="name" maxlength="20"  autocomplete="off">

2  但是有一种情况例外,就是表单中有input[type="password"],点击保存密码后,在Chrome浏览器则自动填充了用户名和密码的输入框;为了统一样式,我们需要就对Chrome的问题经行单独处理。

总结了5种解决方案,如下:

1 修改value值(目前已失效,随着chrome版本的升级,现今版本已不再能获取到value值了,所以无法对其进行操作,貌似chrome自动填充的表单的value值是存在 DocumentFragment里的div中的,暂不知道怎么去处理,等待大神告知)

if(navigator.userAgent.toLowerCase().indexOf("chrome") != -1){
			var inputers = document.getElementsByTagName("input");
			for(var i=0;i<inputers.length;i++){
				if((inputers[i].type !== "submit") && (inputers[i].type !== "password")){
					inputers[i].value = " ";
				}
			}
			setTimeout(function(){
				for(var i=0;i<inputers.length;i++){
					if(inputers[i].type !== "submit"){
						inputers[i].value = "";
					}
				}
			},100)
		}

2 修改disabled属性

if(navigator.userAgent.toLowerCase().indexOf("chrome") != -1){
			var inputers = document.getElementsByTagName("input");
			for(var i=0;i<inputers.length;i++){
				if((inputers[i].type !== "submit") && (inputers[i].type !== "password")){
					inputers[i].disabled= true;
				}
			}
			setTimeout(function(){
				for(var i=0;i<inputers.length;i++){
					if(inputers[i].type !== "submit"){
						inputers[i].disabled= false;
					}
				}
			},100)
		}

3 去除输入框的name和id属性

if(navigator.userAgent.toLowerCase().indexOf("chrome") != -1){
			var inputers = document.getElementsByTagName("input");
			for(var i=0;i<inputers.length;i++){
				if((inputers[i].type !== "submit") && (inputers[i].type !== "password")){
					var input = inputers[i];
					var inputName = inputers[i].name;
					var inputid = inputers[i].id;
					inputers[i].removeAttribute("name");
					inputers[i].removeAttribute("id");
					setTimeout(function(){
						input.setAttribute("name",inputName);
						input.setAttribute("id",inputid);
					},1)
				}
			}
		}

4 可以在不需要默认填写的input框中设置 autocomplete="new-password"

网上咱没有找到对其详细解释,但是发现163邮箱的登录注册是这么用的,


所以就借鉴借鉴咯,测试之后也是可以解决问题的,也是最简单的解决办法,网易给您点个赞!

5 修改readonly属性

<input type="password" readonly οnfοcus="this.removeAttribute('readonly');"/>


参考来源:

http://stackoverflow.com/questions/15738259/disabling-chrome-autofill/29582380#29582380

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章