Wednesday, May 23, 2018

How to Disable Browser Autocomplete in a Password Box

Most modern browsers are coded to ignore autocomplete="off" on an <input type="password"> field, with the assumption that the site is just trying to be annoying and that the user should be allowed to save and autocomplete their password if they want to.

Most of the time, this is what the user wants. Most sites only have one place and one use case for entering a password: signing in. Some sites also require verification of the password for sensitive operations. Again, the assumption of "if the user wants to save the password, let them" might be OK for these situations as well.

Where this really breaks down is administrative uses.

If I'm an admin and I want to create users, in some applications, I need to set their password. Having the site autocomplete my password, is at best annoying, and could be a security concern.

There are also other uses of <input type="password">: credit card CCV codes, security question/answers, cryptographic keys, etc. and having the browser autocomplete your password is not a good idea.

In these cases, you need/want to disable autocomplete. This is the way I've found that seems to work in the latest version of IE, Firefox, Chrome, and Edge.

<input id="password" name="password" type="password"
 autocomplete="new-password"
 readonly="readonly"
 style="background-color:#fff" />

<script>
setTimeout(function() {
 $("#password").prop("readonly", false).css("background-color", "");
}, 50);
</script>

Starting out in readonly mode is enough for IE, Firefox, and Edge, but has no effect in Chrome. The background-color style just resets the style so it doesn't appear grayed out when the page first loads. The <script> is needed to enable the field after the page has loaded. I tried enabling it when the document loads (e.g. $(function() { ... })), but in Firefox, it triggered the autocomplete anyway. Introducing the delay was the only way to get it to work (50 ms seems to work in my testing - a 10 ms delay didn't work reliably).

I like the autocomplete="new-password" method and wish browsers would standardize around this (since they don't want to use the current standard of "off"). This attribute value works in current versions of Chrome (66.0.3359.181 at the time of this writing) and was the only thing that worked in Chrome, but has no effect in other browsers.