在许多用户共享一个计算机并存储敏感信息的情况下,我们需要禁用密码自动填充功能。一开始我尝试了您的“简单而优雅”的隐藏密码解决方案,但是一个聪明的用户向我展示了任何人都可以使用浏览器的开发人员工具来在隐藏字段中以纯文本显示以前用户的自动填充密码。
以下是我安全地禁用密码自动填充的方法。这在Firefox 29和IE8上运行:
动态创建密码字段,并在页面加载时将其附加到表单中。给它一个占位符属性。
function createPasswordInput() {
var dynpass = document.createElement("input");
dynpass.setAttribute("type", "password");
dynpass.setAttribute("size", 32);
dynpass.setAttribute("id", "dynPwElem");
dynpass.setAttribute("placeholder", "Enter password");
var td = document.getElementById("dynamicTd");
td.appendChild(dynpass);
var rpw = document.getElementById("dynPwElem");
rpw.setAttribute("name", "userPassword");
rpw.maxLength = "1";
将密码元素的maxLength属性设置为1,并附加一个onfocus事件以将maxLength扩展到应有的长度(在我的情况下为32)。
function expandPwLength() {
var rpw = document.getElementById("dynPwElem");
if (rpw.maxLength < 32) {
rpw.maxLength = 32;
}
}
if (rpw.addEventListener) {
rpw.addEventListener("focus", expandPwLength, true);
} else {
rpw.attachEvent("onfocus", expandPwLength);
}
如果用户在用户ID字段中按下“Enter”键,则使用按键事件侦听器防止表单提交。相反,将插入符号移动到密码字段。
function preventAutocomplete (charCode) {
if (charCode == 13) {
document.getElementById("dynPwElem").focus();
}
}
}
在相同的按键事件监听器中,截断密码元素的自动完成属性。
if (charCode == 13 || charCode == 40) // the Enter key, or the Down-arrow key
document.forms["loginSubmitForm"].userPassword.autocomplete = "";
在页面加载时使用JavaScript设置整个表单属性"autocomplete"为"off",而不是在HTML标签中。
document.forms["loginSubmitForm"].autocomplete="off";