[html] How to prevent a browser from storing passwords

I need to stop browsers from storing the username & password values, because I'm working on a web application which contains more secure data. My client asked me to do this.

I tried the autocomplete="off" attribute in the HTML form and password fields. But it is not working in the latest browsers like Chrome 55, Firefox 38+, Internet Explorer 11, etc.

What is the best solution for this?

This question is related to html security browser

The answer is


One way would be to generate random input names and work with them.

This way, browsers will be presented with the new form each time and won't be able to pre-populate the input fields.

If you provide us with some sample code (do you have a JavaScript single-page application (SPA) app or some server side rendering) I would be happy to help you in the implementation.


I tested the many solutions and finally I came with this solution.

HTML Code

<input type="text" name="UserName" id="UserName" placeholder="UserName" autocomplete="off" />
<input type="text" name="Password" id="Password" placeholder="Password" autocomplete="off"/>

CSS Code

#Password {
    text-security: disc;
    -webkit-text-security: disc;
    -moz-text-security: disc;
}

JavaScript Code

window.onload = function () {
    init();
}

function init() {
    var x = document.getElementsByTagName("input")["Password"];
    var style = window.getComputedStyle(x);
    console.log(style);

    if (style.webkitTextSecurity) {
        // Do nothing
    } else {
        x.setAttribute("type", "password");
    }
}

In such a situation, I populate the password field with some random characters just after the original password is retrieved by the internal JavaScript code, but just before the form submission.

NOTE: The actual password is surely used for the next step by the form. The value is transferred to a hidden field first. See the code example.

That way, when the browser's password manager saves the password, it is not really the password the user had given there. So the user thinks the password has been saved, when in fact some random stuff is what got saved. Over time, the user would know that he/she can't trust the password manager to do the right job for that site.

Now this can lead to a bad user experience; I know because the user may feel that the browser has indeed saved the password. But with adequate documentation, the user can be consoled. I feel this is the way one can fully be sure that the actual password entered by the user cannot be picked up by the browser and saved.

<form id='frm' action="https://google.com">
    Password: <input type="password" id="pwd" />
    <input type='hidden' id='hiddenpwd' />
    <button onclick='subm()'>Submit this</button>
</form>

<script>
    function subm() {
        var actualpwd = $('#pwd').val();
        $('#hiddenpwd').val(actualpwd);
        // ...Do whatever Ajax, etc. with this actual pwd
        // ...Or assign the value to another hidden field
        $('#pwd').val('globbedygook');
        $('#frm').submit();
    }
</script>

< input type="password" style='pointer-event: none' onInput= (e) => handleInput(e) />
function handleInput(e) {
  e.preventDefault();
  e.stopPropagation();
  e.target.setAttribute('readonly', true);
  setTimeout(() => {
    e.target.focus();
    e.target.removeAttribute('readonly');
  });
}

At the time this was posted, neither of the previous answers worked for me.

This approach uses a visible password field to capture the password from the user and a hidden password field to pass the password to the server. The visible password field is blanked before the form is submitted, but not with a form submit event handler (see explanation on the next paragraph). This approach transfers the visible password field value to the hidden password field as soon as possible (without unnecessary overhead) and then wipes out the visible password field. If the user tabs back into the visible password field, the value is restored. It uses the placeholder to display ??? after the field was wiped out.

I tried clearing the visible password field on the form onsubmit event, but the browser seems to be inspecting the values before the event handler and prompts the user to save the password. Actually, if the alert at the end of passwordchange is uncommented, the browser still prompts to save the password.

_x000D_
_x000D_
function formsubmit(e) {
  document.getElementById('form_password').setAttribute('placeholder', 'password');
}

function userinputfocus(e) {
  //Just to make the browser mark the username field as required
  // like the password field does.
  e.target.value = e.target.value;
}

function passwordfocus(e) {
  e.target.setAttribute('placeholder', 'password');
  e.target.setAttribute('required', 'required');
  e.target.value = document.getElementById('password').value;
}

function passwordkeydown(e) {
  if (e.key === 'Enter') {
    passwordchange(e.target);
  }
}

function passwordblur(e) {
  passwordchange(e.target);

  if (document.getElementById('password').value !== '') {
    var placeholder = '';
      
    for (i = 0; i < document.getElementById('password').value.length; i++) {
      placeholder = placeholder + '?';
    }
      
    document.getElementById('form_password').setAttribute('placeholder', placeholder);
  } else {
    document.getElementById('form_password').setAttribute('placeholder', 'password');
  }
}

function passwordchange(password) {
  if (password.getAttribute('placeholder') === 'password') {
    if (password.value === '') {
      password.setAttribute('required', 'required');
    } else {
      password.removeAttribute('required');
      var placeholder = '';

      for (i = 0; i < password.value.length; i++) {
        placeholder = placeholder + '?';
      }
    }

    document.getElementById('password').value = password.value;
    password.value = '';

    //This alert will make the browser prompt for a password save
    //alert(e.type);
  }
}
_x000D_
#form_password:not([placeholder='password'])::placeholder {
  color: red; /*change to black*/
  opacity: 1;
}
_x000D_
<form onsubmit="formsubmit(event)" action="/action_page.php">
<input type="hidden" id="password" name="password" />

<input type="text" id="username" name="username" required
  autocomplete="off" placeholder="username"
  onfocus="userinputfocus(event)" />
<input type="password" id="form_password" name="form_password" required
  autocomplete="off" placeholder="password"
  onfocus="passwordfocus(event)"
  onkeydown="passwordkeydown(event)"
  onblur="passwordblur(event)"/>
<br />
<input type="submit"/>
_x000D_
_x000D_
_x000D_


Here is a pure HTML/CSS solution for Chrome tested in version 65.0.3325.162 (official build) (64-bit).

Set the input type="text" and use CSS text-security:disc to mimic type="password".

<input type="text" name="username">
<input type="text" name="password" style="text-security:disc; -webkit-text-security:disc;">

As far as I have tested this solution works for Chrome, Firefox version 59.0 (64-bit), Internet Explorer version 11.0.9600 as well as the IE Emulators Internet Explorer 5 and greater.


I just change the type attribute of the field password to hidden before the click event:

document.getElementById("password").setAttribute("type", "hidden");
document.getElementById("save").click();

I would create a session variable and randomize it. Then build the id and name values based on the session variable. Then on login interrogate the session var you created.

if (!isset($_SESSION['autoMaskPassword'])) {
    $bytes = random_bytes(16);
    $_SESSION['autoMask_password'] = bin2hex($bytes);
}

<input type="password" name="<?=$_SESSION['autoMaskPassword']?>" placeholder="password">

I think it is not possible in the latest browsers.

The only way you can do that is to take another hidden password field and use it for your logic after taking value from visible password field while submitting and put dummy string in visible password field.

In this case the browser can store a dummy string instead of the actual password.


It is working fine for a password field to prevent to remember its history:

_x000D_
_x000D_
$('#multi_user_timeout_pin').on('input keydown', function(e) {_x000D_
  if (e.keyCode == 8 && $(this).val().length == 1) {_x000D_
    $(this).attr('type', 'text');_x000D_
    $(this).val('');_x000D_
  } else {_x000D_
    if ($(this).val() !== '') {_x000D_
      $(this).attr('type', 'password');_x000D_
    } else {_x000D_
      $(this).attr('type', 'text');_x000D_
    }_x000D_
  }_x000D_
_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" id="multi_user_timeout_pin" name="multi_user_pin" autocomplete="off" class="form-control" placeholder="Type your PIN here" ng-model="logutUserPin">
_x000D_
_x000D_
_x000D_


While the previous solutions are very correct, if you absolutely need the feature then you can mimic the situation with custom input using text-field and JavaScript.

For secure usage, you can use any cryptography technique. So this way you will bypass the browser's password saving behavior.

If you want to know more about the idea, we can discuss that on chat. But the gist is discussed in previous answers and you can get the idea.


I solved this by adding autocomplete="one-time-code" to the password input.

As per an HTML reference autocomplete="one-time-code" - a one-time code used for verifying user identity. It looks like the best fit for this.


You should be able to make a fake hidden password box to prevent it.

_x000D_
_x000D_
<form>_x000D_
  <div style="display:none">_x000D_
    <input type="password" tabindex="-1"/>_x000D_
  </div>_x000D_
  <input type="text" name="username" placeholder="username"/>_x000D_
  <input type="password" name="password" placeholder="password"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_


I did it by setting the input field as "text", and catching and manipulating the input keys

first activate a function to catch keys

yourInputElement.addEventListener('keydown', onInputPassword);

the onInputPassword function is like this: (assuming that you have the "password" variable defined somewhere)

onInputPassword( event ) {
  let key = event.key;
  event.preventDefault(); // this is to prevent the key to reach the input field

  if( key == "Enter" ) {
    // here you put a call to the function that will do something with the password
  }
  else if( key == "Backspace" ) {
    if( password ) {
      // remove the last character if any
      yourInputElement.value = yourInputElement.value.slice(0, -1);
      password = password.slice(0, -1);
    }
  }
  else if( (key >= '0' && key <= '9') || (key >= 'A' && key <= 'Z') || (key >= 'a' && key <= 'z') ) {
    // show a fake '*' on input field and store the real password
    yourInputElement.value = yourInputElement.value + "*";
    password += key;
  }
}

so all alphanumeric keys will be added to the password, the 'backspace' key will erase one character, the 'enter' key will terminate, and any other keys will be ignored

don't forget to call removeEventListener('keydown', onInputPassword) somewhere at the end


Try the following. It may be help you.

For more information, visit Input type=password, don't let browser remember the password

_x000D_
_x000D_
function setAutoCompleteOFF(tm) {_x000D_
    if(typeof tm == "undefined") {_x000D_
        tm = 10;_x000D_
    }_x000D_
    try {_x000D_
        var inputs = $(".auto-complete-off, input[autocomplete=off]");_x000D_
        setTimeout(function() {_x000D_
            inputs.each(function() {_x000D_
                var old_value = $(this).attr("value");_x000D_
                var thisobj = $(this);_x000D_
                setTimeout(function() {_x000D_
                    thisobj.removeClass("auto-complete-off").addClass("auto-complete-off-processed");_x000D_
                    thisobj.val(old_value);_x000D_
                }, tm);_x000D_
             });_x000D_
         }, tm);_x000D_
    }_x000D_
    catch(e){_x000D_
    }_x000D_
}_x000D_
_x000D_
$(function(){_x000D_
    setAutoCompleteOFF();_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="passfld" type="password" autocomplete="off" />_x000D_
<input type="submit">
_x000D_
_x000D_
_x000D_


I needed this a couple of years ago for a specific situation: Two people who know their network passwords access the same machine at the same time to sign a legal agreement.

You don't want either password saved in that situation because saving a password is a legal issue, not a technical one where both the physical and temporal presence of both individuals is mandatory. Now, I'll agree that this is a rare situation to encounter, but such situations do exist and built-in password managers in web browsers are unhelpful.

My technical solution to the above was to swap between password and text types and make the background color match the text color when the field is a plain text field (thereby continuing to hide the password). Browsers don't ask to save passwords that are stored in plain text fields.

jQuery plugin:

https://github.com/cubiclesoft/php-flexforms-modules/blob/master/password-manager/jquery.stoppasswordmanager.js

Relevant source code from the above link:

(function($) {
$.fn.StopPasswordManager = function() {
    return this.each(function() {
        var $this = $(this);

        $this.addClass('no-print');
        $this.attr('data-background-color', $this.css('background-color'));
        $this.css('background-color', $this.css('color'));
        $this.attr('type', 'text');
        $this.attr('autocomplete', 'off');

        $this.focus(function() {
            $this.attr('type', 'password');
            $this.css('background-color', $this.attr('data-background-color'));
        });

        $this.blur(function() {
            $this.css('background-color', $this.css('color'));
            $this.attr('type', 'text');
            $this[0].selectionStart = $this[0].selectionEnd;
        });

        $this.on('keydown', function(e) {
            if (e.keyCode == 13)
            {
                $this.css('background-color', $this.css('color'));
                $this.attr('type', 'text');
                $this[0].selectionStart = $this[0].selectionEnd;
            }
        });
    });
}
}(jQuery));

Demo:

https://barebonescms.com/demos/admin_pack/admin.php

Click "Add Entry" in the menu and then scroll to the bottom of the page to "Module: Stop Password Manager".


By default, there is not any proper answer to disable saving a password in your browser. But luckily there is a way around and it works in almost all the browsers.

To achieve this, add a dummy input just before the actual input with autocomplete="off" and some custom styling to hide it and providing tabIndex.

Some browsers' (Chrome) autocomplete will fill in the first password input it finds, and the input before that, so with this trick it will only fill in an invisible input that doesn't matter.

          <div className="password-input">
            <input
              type="password"
              id="prevent_autofill"
              autoComplete="off"
              style={{
                opacity: '0',
                position: 'absolute',
                height: '0',
                width: '0',
                padding: '0',
                margin: '0'
              }}
              tabIndex="-2"
            />
            <input
              type="password"
              autoComplete="off"
              className="password-input-box"
              placeholder="Password"
              onChange={e => this.handleChange(e, 'password')}
            />
          </div>

This worked for me:

<form action='/login' class='login-form' autocomplete='off'>
  User:
  <input type='user' name='user-entry'>
  <input type='hidden' name='user'>

  Password:
  <input type='password' name='password-entry'>
  <input type='hidden' name='password'>
</form>

This is not possible in modern browsers, and for good reason. Modern browsers offer password managers, which enable users to use stronger passwords than they would usually.

As explained by MDN: How to Turn Off Form Autocompletion:

Modern browsers implement integrated password management: when the user enters a username and password for a site, the browser offers to remember it for the user. When the user visits the site again, the browser autofills the login fields with the stored values.

Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details.

Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise.

For this reason, many modern browsers do not support autocomplete="off" for login fields:

  • If a site sets autocomplete="off" for a form, and the form includes username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

  • If a site sets autocomplete="off" for username and password input fields, then the browser will still offer to remember this login, and if the user agrees, the browser will autofill those fields the next time the user visits the page.

This is the behavior in Firefox (since version 38), Google Chrome (since 34), and Internet Explorer (since version 11).

If an author would like to prevent the autofilling of password fields in user management pages where a user can specify a new password for someone other than themself, autocomplete="new-password" should be specified, though support for this has not been implemented in all browsers yet.


One thing you can do is ask your users to disable saving the password for your site. This can be done browser wide or origin wide.

Something else you can do is to force the inputs to be empty after the page is loaded (and after the browser auto completed the fields). Put this script at the end of the <body> element.

userIdInputElement.value = "";
userPasswordInputElement.value = "";

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to security

Monitoring the Full Disclosure mailinglist Two Page Login with Spring Security 3.2.x How to prevent a browser from storing passwords JWT authentication for ASP.NET Web API How to use a client certificate to authenticate and authorize in a Web API Disable-web-security in Chrome 48+ When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site? How does Content Security Policy (CSP) work? How to prevent Screen Capture in Android Default SecurityProtocol in .NET 4.5

Examples related to browser

How to force reloading a page when using browser back button? How do we download a blob url video How to prevent a browser from storing passwords How to Identify Microsoft Edge browser via CSS? Edit and replay XHR chrome/firefox etc? Communication between tabs or windows How do I render a Word document (.doc, .docx) in the browser using JavaScript? "Proxy server connection failed" in google chrome Chrome - ERR_CACHE_MISS How to check View Source in Mobile Browsers (Both Android && Feature Phone)