Explain Codes LogoExplain Codes Logo

How to prevent a browser from storing passwords

html
autocomplete
password-security
browser-behavior
Alex KataevbyAlex Kataev·Jan 27, 2025
TLDR

To prevent a browser from saving passwords, implement the autocomplete="off" setting:

<form autocomplete="off"> <input type="password" autocomplete="new-password"> </form>

Also, apply autocomplete="new-password" property to the password field to deter autofill.

Read-only attribute and onfocus event

Increase security levels with readonly and onfocus attributes:

<!-- Readonly attribute tells the browser "Hey, hands off!" --> <input type="password" readonly onfocus="this.removeAttribute('readonly');">

When the user focuses on the password field, the readonly attribute gets removed, and the browser won't store the password.

Handling stubborn browsers

Certain browsers may ignore autocomplete="off". Trick them by placing a hidden input field before the actual password field:

<!-- Nothing to see here, browser, move along --> <input type="password" tabindex="-1" style="display: none; visibility: hidden;"> <input type="password">

The hidden input might distract the browser's autofill and protect the true password field from getting stored.

Advanced security tactics

Creating faux password fields

A good dose of deception can go a long way. Use CSS text-security on a text input field, giving the appearance of a password field:

<!-- This isn't the password you're looking for --> <style> input[type="text"].password { text-security: disc; -webkit-text-security: disc; } </style> <input type="text" class="password">

For Firefox, use a custom font-family setting to mimic password field's style:

@font-face { font-family: 'passwordDot'; src: local('passwordDot'); } input[type="text"].password { font-family: 'passwordDot'; }

More autocomplete options

autocomplete="new-password" and autocomplete="one-time-code" each serve unique purposes. Set autocomplete="new-password" for new registrations or password resets, hinting the browser not to store the input. Use autocomplete="one-time-code" for fields that handle single-use code, generally sent via SMS.

Browser peculiarities and security measures

Keep in mind that browsers are designed with user privacy first. While these can enhance security, they often overrule HTML attributes such as autocomplete for better user data protection. Therefore, remember to test your measures on various browsers to ensure optimal consistency and security.