Disable form autofill in Chrome without disabling autocomplete [duplicate]
Asked Answered
H

21

51

How can we disable Chrome's autofill feature on certain <input>s to prevent them from being automatically populated when the page loads?

At the same time I need to keep autocomplete enabled, so the user can still see the list of suggestions by clicking on the input or typing in it. Can this be done?

EDIT: Feel free to use plain Javascript or jQuery if you feel it is necessary or you feel like it would make your solution simpler.

Hallucinosis answered 7/6, 2012 at 19:53 Comment(10)
Possibly (because it may not allow for any autocomplete actions) related: #3000078Birthstone
I tried autocomplete="off" and it stopped the browser from autofilling the inputs when the page loaded but it also prevented the suggestions from coming up when I typed or clicked in the inputs. I tried value="" and other similar things and it didn't do anything. I tried removing the value attribute and it didn't do anything.Hallucinosis
I tried naming the field a different thing but in my situation, it would be tricky to keep things working on the server if I did that.Hallucinosis
Yeah, I was afraid of that happening. Not sure what to suggest.Birthstone
@mikez302 Have you tried my solution? I'm interested to know if it worked for you, or if I should start looking for another answer to this problem.Tieshatieup
I tried your example and it seems to work fine. I still don't like the idea that there can be some strange value that can cause problems, and it is not completely unconceivable that someone will come up with a solution that doesn't have this problem, so I will probably wait until the bounty period is almost over before I decide who to award the bounty to. I would like it if you or someone else could come up with another answer.Hallucinosis
I added a second solution to my answer that solves the problem you have with the first.Tieshatieup
The best solution for this which probably helps you is this: #2920806Gummous
Please check my workaround here: https://mcmap.net/q/57902/-disabling-chrome-autofill/…Prolusion
If you would like to use JavaScript to solve this problem, try github.com/terrylinooo/disableautofill.jsAron
S
86

Here's the magic you want:

    autocomplete="new-password"

Chrome intentionally ignores autocomplete="off" and autocomplete="false". However, they put new-password in as a special clause to stop new password forms from being auto-filled.

I put the above line in my password input, and now I can edit other fields in my form and the password is not auto-filled.

Sexton answered 11/4, 2016 at 2:29 Comment(5)
This is the correct solution, if your goal is to prevent a password autofill.Muenster
From a usability and accessibility standpoint, this is the only acceptable solution.Bilateral
but wont new-password iirc also kill the autocomplete? the title said that this excplicitly should NOT happen.Concupiscence
@Concupiscence I think you're right. To Chrome, they are two parts of the same feature. So this answer is for people trying to disable bothSexton
Doesn't work for me on Chrome 103.Divorcee
G
43

A little late, but here's my fool proof solution useful for pages like the sign up/registration page where the user has to input a new password.

<form method="post">
    <input type="text" name="fname" id="firstname" x-autocompletetype="given-name" autocomplete="on">
    <input type="text" name="lname" id="lastname" x-autocompletetype="family-name" autocomplete="on">
    <input type="text" name="email" id="email" x-autocompletetype="email" autocomplete="on">
    <input type="password" name="password" id="password_fake" class="hidden" autocomplete="off" style="display: none;">
    <input type="password" name="password" id="password" autocomplete="off">
</form>

Chrome will detect two password inputs and will not auto fill the password fields. However, the field id="password_fake" one will be hidden via CSS. So the user will only see one password field.

I've also added some extra attributes "x-autocompletetype" which is a chrome experimental specific auto fill feature. From my example, chrome will autofill in the first name, last name and email address, and NOT the password field.

Gilreath answered 4/10, 2013 at 5:59 Comment(2)
Only solution working for me.Craggie
Messy, but at least it worked. Interestingly, I also have autocomplete="off" set on this form, and while that worked for Firefox, it wasn't enough for Chrome (possibly for good reason).Ebonyeboracum
M
27

Fix: prevent browser autofill in

 <input type="password" readonly onfocus="this.removeAttribute('readonly');"/>

Update: Mobile Safari sets cursor in the field, but does not show virtual keyboard. New Fix works like before but handles virtual keyboard:

<input id="email" readonly type="email" onfocus="if (this.hasAttribute('readonly')) {
    this.removeAttribute('readonly');
    // fix for mobile safari to show virtual keyboard
    this.blur();    this.focus();  }" />

Live Demo https://jsfiddle.net/danielsuess/n0scguv6/

// UpdateEnd

Explanation Instead of filling in whitespaces or window-on-load functions this snippet works by setting readonly-mode and changing to writable if user focuses this input field (focus contains mouse click and tabbing through fields).

No jQuery needed, pure JavaScript.

Mercury answered 22/2, 2015 at 20:59 Comment(1)
This gets around a lot of the strange heuristic Chrome idiocy... thanks a lot! It's finally not auto-completing the username in the search field!!Nombles
S
12

After a lot of struggle, I have found that the solution is a lot more simple that you could imagine:

Instead of autocomplete="off" just simply use autocomplete="false" ;)

Try this...

$(document).ready(function () {
    $('input').attr('autocomplete', 'false');
});
Sandfly answered 21/5, 2015 at 11:1 Comment(4)
A little late but...It disables the entire form not just one inputHewes
@HFR1994, you could fix that by changing it to $('input#password').attr('autocomplete', 'false');Involved
@Involved thumbs up, your rightHewes
This don't work with chrome 88Salmons
D
10

I stumbled upon the weird chrome autofill behaviour today. It happened to enable on fields called: "embed" and "postpassword" (filling there login and password) with no apparent reason. Those fields had already autocomplete set to off.

None of the described methods seemed to work. None of the methods from the another answer worked as well. I came upon my own idea basing on Steele's answer (it might have actually worked, but I require the fixed post data format in my application):

Before the real password, add those two dummy fields:

<input type='text' style='display: none'>
<input type='password' style='display: none'>

Only this one finally disabled autofill altogether for my form.

It's a shame, that disabling such a basic behavior is that hard and hacky.

Driveway answered 10/4, 2014 at 10:4 Comment(0)
A
4

I'm not able to get my Chrome to autofill automatically on page load to test this, but you can try adding autocomplete="off" to your fields, then removing the attribute on load:

$(window).load(function() { // can also try on document ready
    $('input[autocomplete]').removeAttr('autocomplete');
});
Andrew answered 17/6, 2012 at 16:23 Comment(6)
This is not helpful. It disables autofill but it also disables autocomplete. See my question.Hallucinosis
@mikez302 Removing the autocomplete attribute restores autocomplete, see jsfiddle.net/jefferyto/fhT9m. Perhaps you can try it before downvoting.Andrew
I tried it and it did not disable autocomplete for me. I don't know why. It seems like it would work.Hallucinosis
I tested your solution some more and it is behaving strangely. Typing in the box does not trigger the autocomplete suggestions but pressing the down arrow key in the box while it is empty does. This is stranger and more complicated than I thought it would be. Sorry for downvoting your answer. I thought you just didn't understand the question.Hallucinosis
@mikez302 Can you post a jsFiddle with the behaviour that you're are seeing?Andrew
I want to stop the auto fill, and this answer did the trick, but how it works?Shaver
G
4

Not a beautiful solution, but worked on Chrome 56:

<INPUT TYPE="text" NAME="name" ID="name" VALUE=" ">
<INPUT TYPE="password" NAME="pass" ID="pass">

Note a space on the value. And then:

$(document).ready(function(){
   setTimeout(() => $('#name').val(''),1000);
});
Gad answered 2/3, 2017 at 21:40 Comment(1)
Finally! Only thing I've found that works. NiceRecipience
B
2

This might help: https://mcmap.net/q/57964/-google-chrome-form-autofill-and-its-yellow-background

if (navigator.userAgent.toLowerCase().indexOf("chrome") >= 0) {
    $(window).load(function(){
        $('input:-webkit-autofill').each(function(){
            var text = $(this).val();
            var name = $(this).attr('name');
            $(this).after(this.outerHTML).remove();
            $('input[name=' + name + ']').val(text);
        });
    });
}

It looks like on load, it finds all inputs with autofill, adds their outerHTML and removes the original, while preserving value and name (easily changed to preserve ID etc)

If this preserves the autofill text, you could just set

var text = "";   /* $(this).val(); */

From the original form where this was posted, it claims to preserve autocomplete. :)

Good luck!

Broadfaced answered 19/6, 2012 at 14:35 Comment(1)
This seemed to keep autofill enabled. It just prevented the background of the input from turning yellow like it usually does with autofill.Hallucinosis
T
1

One solution would be to auto-fill the inputs with whitespace characters, and have them clear on focus.

Example: http://nfdb.net/autofill.php

<!doctype html>
<html>
    <head>
        <title>Autofill Test</title>
        <script>
            var userfield;

            // After the document has loaded, manipulate DOM elements.
            window.addEventListener('load', function() {

                // Get the username field element.
                userfield = document.getElementById('user');

                // Listen to the 'focus' event on the input element.
                userfield.addEventListener('focus', function() {

                    // Checks if the value is the EM space character,
                    // and removes it when the input is recieves focus.
                    if (this.value == '\u2003') this.value = ''

                }, false);

                // Listen to the 'blur' event on the input element.
                // Triggered when the user focuses on another element or window.
                userfield.addEventListener('blur', function() {

                    // Checks if the value is empty (the user hasn't typed)
                    // and inserts the EM space character if necessary.
                    if (this.value == '') this.value = '\u2003';

                }, false);
            }, false);
        </script>
    </head>
    <body>
        <form method="GET" action="">
            <input id="user" name="username" type="text" value="&#8195;"/><br/>
            <input name="password" type="password" value=""/><br/>
            <input type="submit" value="Login">
        </form>
    </body>
</html>

This should stop the browser from auto-filling the fields, but still allow them to auto-complete.

Here's another example that clears the form inputs after the page loads. The advantage of this method is that the inputs never have any whitespace characters in them, the disadvantage is that there's a small possibility that the auto-filled values may be visible for a few milliseconds.

http://nfdb.net/autofill2.php

<!doctype html>
<html>
    <head>
        <title>Autofill Test</title>
        <script>
            var userfield, passfield;

            // Wait for the document to load, then call the clear function.
            window.addEventListener('load', function() {

                // Get the fields we want to clear.
                userfield = document.getElementById('user');
                passfield = document.getElementById('pass');

                // Clear the fields.
                userfield.value = '';
                passfield.value = '';

                // Clear the fields again after a very short period of time, in case the auto-complete is delayed.
                setTimeout(function() { userfield.value = ''; passfield.value = ''; }, 50);
                setTimeout(function() { userfield.value = ''; passfield.value = ''; }, 100);

            }, false);
        </script>
    </head>
    <body>
        <div>This form has autofill disabled:</div>
        <form name="login" method="GET" action="./autofill2.php">
            <input id="user" name="username" type="text" value=""/><br/>
            <input id="pass" name="password" type="password" value=""/><br/>
            <input type="submit" value="Login">
        </form>
        <div>This form is untouched:</div>
        <form name="login" method="GET" action="./autofill2.php">
            <input name="username" type="text" value=""/><br/>
            <input name="password" type="password" value=""/><br/>
            <input type="submit" value="Login">
        </form>
    </body>
</html>
Tieshatieup answered 12/6, 2012 at 17:58 Comment(9)
I am willing to consider this although I am worried that it may cause problems in case someone wants to actually enter " " as a value.Hallucinosis
You can use different whitespace characters. Such as an EM space. I simply used normal spaces as an example.Tieshatieup
I've updated the example to be more chrome-friendly, and to use an EM space.Tieshatieup
I'm going to go ahead and add comments to the code. Let me know if there's something you want me to explain in more detail.Tieshatieup
I am not sure if I like your 2nd solution. It seems like if there is any value that is actually in the value attribute in the code coming from the server, that will be erased. I am not trying to erase any value in the input, only inputs that are autofilled.Hallucinosis
If you have a value filled in then you don't need to use this method to stop it from auto filling. This would be a lot easier if you actually showed the code you're working with.Tieshatieup
What if I have some inputs with values filled in and some without? I will need to make some code that fills only the ones without values, and it can get tricky and complicated. So far, your first solution is the best answer I found here.Hallucinosis
The code I have is somewhat complex and uses some server-side code to populate the inputs.Hallucinosis
down side of this, is that the "empty fields" verification, that works by comparing the value with empty-ness won't just work right..?Colchicum
G
1

I was recently faced with this problem, and with no simple solution since my fields can be prepopulated, I wanted to share an elegant hack I came up with by setting password type in the ready event.

Don't declare your input field as type password when creating it, but add a ready event listener to add it for you:

function createSecretTextInput(name,parent){
    var createInput = document.createElement("input");
    createInput.setAttribute('name', name);
    createInput.setAttribute('class', 'secretText');
    createInput.setAttribute('id', name+'SecretText');
    createInput.setAttribute('value', 'test1234');

    if(parent==null)
       document.body.appendChild(createInput);
    else
        document.getElementById(parent).appendChild(createInput);

    $(function(){
        document.getElementById(name+'SecretText').setAttribute('type', 'password');
    });
};

createSecretTextInput('name', null);

http://jsfiddle.net/

Glottology answered 18/7, 2014 at 13:58 Comment(0)
B
0

A bit late to the party... but this is easily done with some jQuery:

$(window).on('load', function() {
    $('input:-webkit-autofill').each(function() {
        $(this).after($(this).clone(true).val('')).remove();
    });
});

Pros

  • Removes autofill text and background color.
  • Retains autocomplete on field.
  • Keeps any events/data bound to the input element.

Cons

  • Quick flash of autofilled field on page load.
Bulb answered 20/7, 2013 at 0:29 Comment(0)
T
0
var fields = $('form input[value=""]');
fields.val(' ');
setTimeout(function() {
    fields.val('');
}, 500);
Tutty answered 17/4, 2014 at 12:54 Comment(0)
F
0

This far I've found this one is working, having to set a Timeout of 1ms for the action to complete after chrome's auto-filling ..

$(window).on('load', function() {
    setTimeout(function(){
        $('input[name*=email],input[name*=Password]').val('-').val(null);
    },1);
});

I'm wondering if there's any way of attaching this function to chrome self-completion firing, or even, redeclaring it

Fan answered 25/8, 2014 at 15:20 Comment(0)
B
0

Chrome password manager is looking for input elements with type="password" and fill in saved password. It also ignores autocomplete="off" property.

Here is fix for latest Chrome (Version 40.0.2181.0 canary):

<input name="password">

JS:

setTimeout(function() {
    var input = document.querySelector("input[name=password]");
    input.setAttribute("type", "password");
}, 0)
Bourse answered 8/10, 2014 at 15:11 Comment(2)
What happens when javascript is not turned on? Then the users passwords are visible for all the peering eyeballs! Oh no!!Devan
@StephenKelzer right, good pointBourse
S
0

autocomplete="off" on the input now working on Chrome V44 (and Canary V47)

Shaver answered 31/8, 2015 at 8:32 Comment(0)
H
0

Easiest solution, provide a value of ' ' for the username field (which you can still call 'username').

If the value can be populated by user-inputted values, as is usually the case for a form that you are validating, provide a value of ' ' when it is not already set. In PHP,

if(trim($username) == ''){$username = ' ';}

<input type='text' value = '$username' name = 'Username' />

I actually think autocompletion for username and password effectively gifts access to all your accounts to anyone who accesses your computer, regardless of how obscure your passwords are...

Harr answered 10/9, 2015 at 16:29 Comment(0)
C
0

My solution is based on dsuess user solution, which didn't work in IE for me, because I had to click one more time in the textbox to be able to type in. Therefore I adapted it only to Chrome:

$(window).on('load', function () {
    if (navigator.userAgent.indexOf("Chrome") != -1) {
        $('#myTextBox').attr('readonly', 'true');
        $('#myTextBox').addClass("forceWhiteBackground");
        $('#myTextBox').focus(function () {
            $('#myTextBox').removeAttr('readonly');
            $('#myTextBox').removeClass('forceWhiteBackground');
        });
    }
});

In your css add this:

.forceWhiteBackground {
    background-color:white !important;
}
Cymose answered 30/12, 2015 at 19:4 Comment(0)
W
0

Here's the latest solution I've discovered. This stops Google filling the fields out and highlighting them yellow before you've even typed anything. Basically, if you put "display:none" on the field Google is smart enough to ignore it and move to the next field. If you put "visibility:hidden" though it counts it as a field in the form which seems to interfer with it's calculations. No javascript needed.

<form method='post'>
    <input type='text' name='u' size='16'/>
    <input type='password' name='fake' size='1' style='width:1px;visibility:hidden'/><br />
    <input type='password' name='p' size='16'/>
</form>
Weariless answered 25/8, 2016 at 13:20 Comment(0)
S
0

I don't like to use setTimeout in or even have strange temporary inputs. So I came up with this.

Simply change your password field type to text

<input name="password" type="text" value="">

And when the user focus that input change it again to password

$('input[name=password]').on('focus', function (e) {
    $(e.target).attr('type', 'password');
});

Its working using latest Chrome (Version 54.0.2840.71 (64-bit))

Singlecross answered 3/11, 2016 at 17:28 Comment(0)
S
-1

Autofill works with name attribute of the input, so if you set a name for an input like "firstname", chrome will fill it.

If you want to disable it, use an odd name like "supermanname".

Javascript can't solve your problem.

Second solution: You can make your inputs hidden with the same names, and set their values with other inputs. I simplified the Js with jQUery.

<form action="handlerfile.php" method="post">
<input type="text" id="1" onclick="$("#2").val($("#1").val())"/>
<input type="hidden" name="username" id="2">
</form>
Streptokinase answered 15/6, 2012 at 15:33 Comment(5)
The problem is, OP wants only the auto-fill disabled, they still want the user to be able to auto-complete the form with data previously entered.Tieshatieup
@Tieshatieup I think this solution does what you described.Fari
Does it? I haven't tested it, but don't the auto-fill and auto-complete both work off the name attribute? If so, removing the name attribute would disable both.Tieshatieup
@Tieshatieup the first input has no name. You think that disables autocomplete?Fari
This looks strange. I don't know if those nested quotes will cause problems, and I don't know if it is valid to begin an id attribute with a digit. Also, I think that picking a strange name like that will disable autocomplete, which I am not trying to do.Hallucinosis
L
-6

You better use disabled for your inputs, in order to prevent auto-completion.

<input type="password" ... disabled />
Literalism answered 31/8, 2015 at 13:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.