禁止input密码自动填充及浏览器记住密码完整解决方案
禁止自动填充方案
html
<input readonly onfocus="this.removeAttribute('readonly')">这方案亲测有效,简单直接,把上面代码直接复制放到input标签就行。
ps:现有的网上多数加隐藏input获取值,都是解决默认填充的,而剩下的方案都是只能实现部分功能。
但是这个方案如果使用password还是会引起浏览器提醒是否保存密码,并不能禁用缓存,只能不自动把账号密码填充进去。
密码类型测试
当type="password"的时候,做了以下测试:
动态设置:初始化为
text,输入之后变为password。失败:在谷歌上,只要设置过password这个input就能引起浏览器反应。禁用事件:因为是input为空的时候,钥匙会消失。输入值就会出现,禁用了input的所有事件的冒泡,默认事件,无效。
禁止表单提交:失败:浏览器并不是在事件机制接受到的触发。
自定义Password组件:原生
password已经没有思路来解决这个问题,所以打造了一个自定义的password。
禁止记住密码方案
使用方法
html
<input type="text" id="password" value="123456a" autocomplete="off">javascript
var password = new Text2Password({
id: "password",
// type:"password", // password 转化为* 其他直接显示
// pattern: /([\u4e00-\u9fa5])/g ,// 接受一个正则,过滤匹配内容
// symbol:"*",// 接受一个字符 作为隐藏的是占位符
callback: function () {
// 数据改变后的回调
console.log(this.value)
}
});
// password.value 取值
// password.$changeType(type) 切换显示状态 传入'password'隐藏 其余正常显示
// password.$setValue(value) 设置值(初始值会自动初始化)已实现功能
- 隐藏真实值
- 解决浏览器记住密码,自动填充,自动弹出记住密码的提示
- 禁止复制,剪切,拖拽,允许粘贴
- 可以在任意位置进行数据插入,删除,替换
- 兼容中文输出(默认正则会过滤中文,但是输入法输入的字母可以正常被输入)
- 兼容谷歌,IE,火狐
Vue 组件版本
javascript
Vue.use(PassWordPlugin)vue
<pass-word :value="value" :type="type"></pass-word>切换数据,按照Vue模式操作传入的value和type即可,监听了后续数据变化。与纯js版本一样,也接受symbol和pattern。
Text2Password.js 核心实现
javascript
; (function (name, definition) {
if (typeof define === 'function') {
define(definition);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = definition();
} else {
this[name] = definition();
}
})('Text2Password', function () {
"use strict";
function Text2Password(opts) {
var id = opts.id,
type = opts.type === undefined ? 'password' : opts.type,
symbol = opts.symbol === undefined ? '*' : opts.symbol,
callback = opts.callback === undefined ? function () { } : opts.callback,
pattern = opts.pattern === undefined ? /([\u4e00-\u9fa5])/g : opts.pattern,
_this = this;
_this.input = document.getElementById(id);
if (!_this.input || _this.input.tagName.toLowerCase() != 'input' || _this.input.type === 'password') {
throw new Error("请传一个type不为password的input的id属性!");
return;
}
_this.input.valueProxy = "";
_this.callback = callback;
_this.type = type;
_this.symbol = symbol;
_this.pattern = pattern;
_this._init();
}
Text2Password.prototype = {
_init: function() {
// 初始化逻辑
},
// ... 其他方法
};
return Text2Password;
});IE可以配合style="ime-mode:disabled"禁用中文输入法。
