解决Chrome的表单自动填充问题

解决Chrome的表单自动填充问题

一般的浏览器都会默认开启一个表单自动填充的功能。这给很多用户带来了方便。但是对于项目开发者来说,有时候这就是噩梦。对安全性有考虑的项目,应该都会考虑到禁用这种自动填充的功能。否则,一个用户登录后,浏览器记住了用户名和密码。当另一个人使用这台电脑时,他肯定不用输入什么,就可以登入别人的账号,这可是很危险的事情。

问题背景

当我使用原始的表单成功登录一次后时,再次打开浏览器,什么都没有输入,就出现了这样的现象。
chrome自动填充

浏览器帮忙记住了用户名和密码。有的人会说,这个OK啊,让用户把浏览器的填充表单的功能禁止掉不就行了?
chrome禁用自动填充

what?你指望让用户来完成本应该由你的程序完成的事情?领盒饭走人吧!

so,怎么解决这个问题呢?

解决过程

首先想到的是通过autocomplete=”off”属性来禁止自动填充,然而发现好像没有起到作用。

接下来我查到的信息是,浏览器会寻找表单中的输入框,自动填充。

1
2
<input type="text">
<input type="password">

灵机一动,我想到在我的真实表单输入框前面放一个隐藏的输入框,如果这个隐藏的输入框代替真实的输入框被浏览器填充,那么问题不久解决了吗。于是,代码变成这样的。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<el-form :model="loginForm" :rules="loginRules" ref="loginForm" class="login-form" autocomplete="off">
<input type="text" name="account" style="display:none;" autocomplete="off"/>
<input type="password" name="password" style="display:none;" autocomplete="off"/>
<div class="formGroup">
<label class="login-label">用户名</label>
<el-form-item prop="account">
<el-input class="login-input" type="text" v-model="loginForm.account" auto-complete="off" placeholder="请输入用户名"></el-input>
</el-form-item>
</div>
<div class="formGroup">
<label class="login-label">密码</label>
<el-form-item prop="password">
<el-input class="login-input" type="password" v-model="loginForm.password" auto-complete="off" placeholder="请输入密码"></el-input>
</el-form-item>
</div>
<div class="formGroup">
<button type="button" class="login-btn" id="btnLogin" @click="login" v-loading="logining">登录</button>
</div>
</el-form>

再次尝试,发现打开登录页后,浏览器没有填充我的el-input了,顿时感觉轻松了下来。然而,当我点击密码框的时候,出现了密码列表。。。坑爹啊!
密码列表

还能怎么办,接着寻找解决方案吧!接下来找了很多方法,尝试后都不是有效的。

于是我尝试先去掉自动填充后的屎黄色。。。
自动填充后的屎黄色

这个填充色是由浏览器伪类input:-webkit-autofill来实现的
-webkit-autofill

于是我加了这些代码

1
2
3
input:-webkit-autofill {
background-color: #fff;
}

但是仍然没有去掉浏览器自带的填充背景色。我就想是不是没有加!important。最后加上了也没有用。看来并不能覆盖掉自带的这个样式属性啊。

在网上搜索后,发现了一个神解决方法,使用盒子阴影来盖住屎黄色,真的可以做到。为这位网友的机智点赞!

1
2
3
4
input:-webkit-autofill {
box-shadow: 0 0 0px 1000px white inset;
-webkit-box-shadow: 0 0 0px 1000px white inset;
}

虽然解决了这个屎黄色背景的问题,但是没有从根本上解决我的需求。接下来的寻找答案的过程中,发现了一个奇妙的解决方案。

1
<el-input class="login-input" type="password" v-model="loginForm.password" auto-complete="new-password" placeholder="请输入密码"></el-input>

就是这么简单,去掉了自动填充的烦人功能。说是autocomplete除了on,off以外的值就可以做到。但是我发现除了new-password,没有其他的值可以有效,Amazing!

问题解决


扫一扫下方小程序码或搜索Tusi博客,即刻阅读最新文章!

Tusi博客

You forgot to set the qrcode for Alipay. Please set it in _config.yml.
You forgot to set the qrcode for Wechat. Please set it in _config.yml.
You forgot to set the business and currency_code for Paypal. Please set it in _config.yml.
You forgot to set the url Patreon. Please set it in _config.yml.
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×