背景
很多用户使用Chrome,Edge浏览器时,默认都开启了自动填充表单,如果需要关闭自动填充,HTML提供了autocomplete
属性,例如设置autocomplete='off'
,然而Chrome、Edge等浏览器并没有遵守这个属性,导致设置了也失效。
通过网上搜索,更改input的name
属性是删除自动填充的唯一方法。
解决方案
通过js批量修改网页中的name属性的值,在原本的值后添加随机数,在提交表单时再修改回来。
例如原本的表单:
<input type="text" name="username" />
修改为:
<input type="text" name="usernameI5NTE" />
js代码:
function stopAutofill()
{
//generate a random string to append to the names
this.autocompleteString = btoa(Math.random().toString()).substr(10, 5);
this.add_submit_handlers = () => {
document.querySelectorAll("form").forEach(value => {
value.addEventListener("submit", (e) => {
this.form_submit_override(e)
})
})
}
//add random characters to input names
this.changeInputNames = () => {
for (var i = 0; i < this.input_elements_arr.length; i++) {
this.input_elements_arr[i].setAttribute("name", this.input_elements_arr[i].getAttribute("name") + this.autocompleteString);
}
}
//remove the random characters from input names
this.changeInputNamesBack = () => {
for (var i = 0; i < this.input_elements_arr.length; i++) {
this.input_elements_arr[i].setAttribute("name", this.input_elements_arr[i].getAttribute("name").replace(this.autocompleteString, ''));
}
}
this.form_submit_override = (e) => {
e.preventDefault()
this.changeInputNamesBack()
e.currentTarget.submit()
return true
}
this.setup_form = () => {
//get all the inputs in the form
this.input_elements_arr = document.querySelectorAll("input");
this.changeInputNames();
this.add_submit_handlers();
}
//make sure script calls function after page load
this.init = () => {
if (document.readyState === "complete") {
this.setup_form()
} else {
let setup_form = this.setup_form
document.addEventListener("DOMContentLoaded", function (e) {
setup_form()
})
}
}
}
//在需要禁用自动填充的页面上调用:
af = new stopAutofill()
af.init()