'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

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