templaedhel
templaedhel

Reputation: 6306

Disabling Chrome Autofill

I have been running into issues with the chrome autofill behavior on several forms.

The fields in the form all have very common and accurate names, such as "email", "name", or "password", and they also have autocomplete="off" set.

The autocomplete flag has successfully disabled the autocomplete behavior, where a dropdown of values appear as you start typing, but has not changed the values that Chrome auto-populates the fields as.

This behavior would be ok except that chrome is filling the inputs incorrectly, for example filling the phone input with an email address. Customers have complained about this, so it's verified to be happening in multiple cases, and not as some some sort of result to something that I've done locally on my machine.

The only current solution I can think of is to dynamically generate custom input names and then extract the values on the backend, but this seems like a pretty hacky way around this issue. Are there any tags or quirks that change the autofill behavior that could be used to fix this?

Upvotes: 618

Views: 1097416

Answers (30)

tibalt
tibalt

Reputation: 16164

June 2023: autocomplete="one-time-code" works in Chrome https://robindirksen.com/blog/html-autocomplete-one-time-code

Apr 2022: autocomplete="off" still does not work in Chrome, and I don't believe it ever has after looking through the Chromium bugs related to the issue (maybe only for password fields). I see issues reported in 2014 that were closed as "WontFix", and issues still open and under discussion [1][2]. From what I gather the Chromium team doesn't believe there is a valid use case for autocomplete="off".

Overall, I still believe that neither of the extreme strategies ("always honor autocomplete=off" and "never honor autocomplete=off") are good.

https://bugs.chromium.org/p/chromium/issues/detail?id=914451#c66

They are under the impression that websites won't use this correctly and have decided not to apply it, suggesting the following advice:

In cases where you want to disable autofill, our suggestion is to utilize the autocomplete attribute to give semantic meaning to your fields. If we encounter an autocomplete attribute that we don't recognize, we won't try and fill it.

As an example, if you have an address input field in your CRM tool that you don't want Chrome to Autofill, you can give it semantic meaning that makes sense relative to what you're asking for: e.g. autocomplete="new-user-street-address". If Chrome encounters that, it won't try and autofill the field.

https://bugs.chromium.org/p/chromium/issues/detail?id=587466#c10

Although this "suggestion" currently works for me it may not always hold true and it looks like the team is running experiments, meaning the autocomplete functionality could change in new releases.

It's silly that we have to resort to this, but the only sure way is to try and confuse the browser as much as possible:

  • Name your inputs without leaking any information to the browser, i.e. id="field1" instead of id="country".

  • Set autocomplete="do-not-autofill", basically use any value that won't let the browser recognize it as an autofillable field.


Jan 2021: autocomplete="off" does work as expected now (tested on Chrome 88 macOS).

For this to work be sure to have your input tag within a Form tag


Sept 2020: autocomplete="chrome-off" disables Chrome autofill.


Original answer, 2015:

For new Chrome versions you can just put autocomplete="new-password" in your password field and that's it. I've checked it, works fine.

Got that tip from Chrome developer in this discussion: https://bugs.chromium.org/p/chromium/issues/detail?id=370363#c7

P.S. Note that Chrome will attempt to infer autofill behavior from name, id and any text content it can get surrounding the field including labels and arbitrary text nodes. If there is a autocomplete token like street-address in context, Chrome will autofill that as such. The heuristic can be quite confusing as it sometimes only trigger if there are additional fields in the form, or not if there are too few fields in the form. Also note that autocomplete="no" will appear to work but autocomplete="off" will not for historical reasons. autocomplete="no" is you telling the browser that this field should be auto completed as a field called "no". If you generate unique random autocomplete names you disable auto complete.

If your users have visited bad forms their autofill information may be corrupt. Having them manually go in and fix their autofill information in Chrome may be a necessary action from them to take.

Upvotes: 1354

mike nelson
mike nelson

Reputation: 22136

I've just found that if you have a remembered username and password for a site, the current version of Chrome will autofill your username/email address into the field before any type=password field. It does not care what the field is called - just assumes the field before password is going to be your username.

Old Solution

Just use <form autocomplete="off"> and it prevents the password prefilling as well as any kind of heuristic filling of fields based on assumptions a browser may make (which are often wrong). As opposed to using <input autocomplete="off"> which seems to be pretty much ignored by the password autofill (in Chrome that is, Firefox does obey it).

Updated Solution

Chrome now ignores <form autocomplete="off">. Therefore my original workaround (which I had deleted) is now all the rage.

Simply create a couple of fields and make them hidden with "display:none". Example:

<!-- fake fields are a workaround for chrome autofill getting the wrong fields -->
<input style="display: none" type="text" name="fakeusernameremembered" />
<input style="display: none" type="password" name="fakepasswordremembered" />

Then put your real fields underneath.

Remember to add the comment or other people on your team will wonder what you are doing!

Update March 2016

Just tested with latest Chrome - all good. This is a fairly old answer now but I want to just mention that our team has been using it for years now on dozens of projects. It still works great despite a few comments below. There are no problems with accessibility because the fields are display:none meaning they don't get focus. As I mentioned you need to put them before your real fields.

If you are using javascript to modify your form, there is an extra trick you will need. Show the fake fields while you are manipulating the form and then hide them again a millisecond later.

Example code using jQuery (assuming you give your fake fields a class):

$(".fake-autofill-fields").show();
// some DOM manipulation/ajax here
window.setTimeout(function () {
  $(".fake-autofill-fields").hide();
}, 1);

Update July 2018

My solution no longer works so well since Chrome's anti-usability experts have been hard at work. But they've thrown us a bone in the form of:

<input type="password" name="whatever" autocomplete="new-password" />

This works and mostly solves the problem.

However, it does not work when you don't have a password field but only an email address. That can also be difficult to get it to stop going yellow and prefilling. The fake fields solution can be used to fix this.

In fact you sometimes need to drop in two lots of fake fields, and try them in different places. For example, I already had fake fields at the beginning of my form, but Chrome recently started prefilling my 'Email' field again - so then I doubled down and put in more fake fields just before the 'Email' field, and that fixed it. Removing either the first or second lot of the fields reverts to incorrect overzealous autofill.

Update Mar 2020

It is not clear if and when this solution still works. It appears to still work sometimes but not all the time.

In the comments below you will find a few hints. One just added by @anilyeni may be worth some more investigation:

As I noticed, autocomplete="off" works on Chrome 80, if there are fewer than three elements in <form>. I don't know what is the logic or where the related documentation about it.

Also this one from @dubrox may be relevant, although I have not tested it:

thanks a lot for the trick, but please update the answer, as display:none; doesn't work anymore, but position: fixed;top:-100px;left:-100px; width:5px; does :)

Update APRIL 2020

Special value for chrome for this attribute is doing the job: (tested on input - but not by me) autocomplete="chrome-off"

Update JUNE 2023

Use autocomplete="new-password"

This is working currently.

Upvotes: 853

Tauras
Tauras

Reputation: 3904

I don't know why, but this helped and worked for me.

<input type="password" name="pwd" autocomplete="new-password">

I have no idea why, but autocomplete="new-password" disables autofill. It worked in latest 49.0.2623.112 chrome version.

Upvotes: 90

hass.
hass.

Reputation: 10

last time I checked Google updated their autofill in JAN 2017, the solution that worked for me was adding another input and hiding it after it has been populated.

 <input type="text" id="phone_number" name="phone_number" value="">
 <input type="text" id="dummy_autocomplete">


<script type="text/javascript">
        $('#dummy_autocomplete').hide();
</script>

Upvotes: -2

Fery Kaszoni
Fery Kaszoni

Reputation: 4040

After months and months of struggle, I have found that the solution is a lot simpler than you could imagine:

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

As simple as that, and it works like a charm in Google Chrome as well!


August 2019 update (credit to @JonEdiger in comments)

Note: lots of info online says the browsers now treat autocomplete='false' to be the same as autocomplete='off'. At least as of right this minute, it is preventing autocomplete for those three browsers.

Set it at form level and then for the inputs you want it off, set to some non-valid value like 'none':

<form autocomplete="off"> 
  <input type="text" id="lastName" autocomplete="none"/> 
  <input type="text" id="firstName" autocomplete="none"/>
</form>

Upvotes: 296

dana
dana

Reputation: 18105

If you are implementing a search box feature, try setting the type attribute to search as follows:

<input type="search" autocomplete="off" />

This is working for me on Chrome v48 and appears to be legitimate markup:

https://www.w3.org/wiki/HTML/Elements/input/search

Upvotes: 103

dsuess
dsuess

Reputation: 5347

Sometimes even autocomplete=off won't prevent filling in credentials into wrong fields.

A workaround is to disable browser autofill using readonly-mode and set writable on focus:

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

The focus event occurs at mouse clicks and tabbing through fields.

Update:

Mobile Safari sets cursor in the field, but does not show virtual keyboard. This new workaround 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: Browser auto fills credentials to wrong text field?

filling the inputs incorrectly, for example filling the phone input with an email address

Sometimes I notice this strange behavior on Chrome and Safari, when there are password fields in the same form. I guess, the browser looks for a password field to insert your saved credentials. Then it autofills username into the nearest textlike-input field , that appears prior the password field in DOM (just guessing due to observation). As the browser is the last instance and you can not control it,

This readonly-fix above worked for me.

Upvotes: 147

norekhov
norekhov

Reputation: 4233

In 2016 Google Chrome started ignoring autocomplete=off though it is in W3C. The answer they posted:

The tricky part here is that somewhere along the journey of the web autocomplete=off become a default for many form fields, without any real thought being given as to whether or not that was good for users. This doesn't mean there aren't very valid cases where you don't want the browser autofilling data (e.g. on CRM systems), but by and large, we see those as the minority cases. And as a result, we started ignoring autocomplete=off for Chrome Autofill data.

Which essentially says: we know better what a user wants.

They opened another bug to post valid use cases when autocomplete=off is required

I haven't seen issues connected with autocomplete throught all my B2B application but only with input of a password type.

Autofill steps in if there's any password field on the screen even a hidden one. To break this logic you can put each password field into it's own form if it doesn't break your own page logic.

<input type=name >

<form>
    <input type=password >
</form>

Upvotes: 10

SaidbakR
SaidbakR

Reputation: 13534

My solution depends on three things thing:

  1. keydown event
  2. masking the field name
  3. blanking the fields values on submit

First of all, we need to prevent autocomplete of both username and password, so, initially we will set two flags, i -> username and j -> passowrd with true value, so without any keydown to the fields both i and j will be true.

In may case the field masking is occured at the server side, by passing random string, it could be made easily made using client side too.

This is the code:

$(document).ready(function(){
   i= true; //username flag
   j= true; // password flag
   $("#username{{$rand}}").keydown(function(e){
          // {{$rand}} is server side value passed in blade view
          // keyboard buttons are clicked in the field
            i = false;       
    });
   $("#passowrd{{$rand}}").keydown(function(e){
          // {{$rand}} is server side value passed in blade view
          // keyboard buttons are clicked in the field
            j = false;       
    });
    // Now we will use change event,
   $("#username{{$rand}}").change(function(){
    if($(this).val() != ''){ //the field has value
        if(i){ // there is no keyboard buttons clicked over it
            $(this).val(''); // blank the field value
        }

    }
})
$("#password{{$rand}}").change(function(){
    if($(this).val() != ''){ // the same as username but using flag j
        if(j){
            $(this).val('');
        }

    }
})

   $("#sForm").submit(function(e){ // the id of my form
      $("#password-s").val($("#password{{$rand}}").val());
        $("#username-s").val($("#username{{$rand}}").val());
        // Here the server will deal with fields names `password` and `username` of the hidden fields
       $("#username{{$rand}}").val('');
        $("#password{{$rand}}").val(''); 

 })
})

Here are the HTML:

<form class="form-horizontal" autocomplete="off" role="form" id="sForm" method="POST" action="https://example.com/login">

                        <input type="hidden" name="password" id="password-s">
                        <input type="hidden" name="username" id="username-s">

                            <label for="usernameTDU3m4d3I5" class="col-md-3 control-label" style="white-space: nowrap">Username</label>

                                <input id="usernameTDU3m4d3I5" placeholder="Username" autocomplete="off" style="border-bottom-left-radius: 10px; border-top-right-radius: 10px; font-family: fixed; font-size: x-large;" type="text" class="form-control" name="usernameTDU3m4d3I5" value="" required="required" autofocus="">                                

                            <label for="passwordTDU3m4d3I5" class="col-md-3 control-label" style="white-space: nowrap">Password</label>
                                <input id="passwordTDU3m4d3I5" placeholder="Password" autocomplete="off" type="password" class="form-control" name="pa-TDU3m4d3I5" required="">


                                <button type="submit" class="btn btn-success">
                                    <i class="fox-login" style="text-shadow: 0px 1px 0px #000"></i><strong>Login</strong>&nbsp;&nbsp;
                                </button>

                                </form>

The above solution, indeed, will not eliminate or prevent the autocomplete of the username and password, but it make that autocomplete useless. i.e without hitting keyboard button on the field, the field value will be blank before submit, so the user will be asked to enter them.

Update

We can, also, use click event to prevent autocomplete from users list appeared under the field like the following:

 $("#username{{$rand}}").click(function(){

            $(this).val('');
            i = true;

})
$("#password{{$rand}}").click(function(){

            $(this).val('');
            j = true;

})

Limitations:

This solution may not work as expected in touch screen devices.

Final Update

I have done the following clean implementation like the following:

preventAutoComplete = true; // modifier to allow or disallow autocomplete
trackInputs = {password:"0", username:"0"}; //Password and username fields ids as object's property, and "0" as its their values
// Prevent autocomplete
    if(preventAutoComplete){
        $("input").change(function(e){ // Change event is fired as autocomplete occurred at the input field 
            trackId = $(this).attr('id'); //get the input field id to access the trackInputs object            
            if (trackInputs[trackId] == '0' || trackInputs[trackId] != $(this).val()){ //trackInputs property value not changed or the prperty value ever it it is not equals the input field value
                $(this).val(''); // empty the field
            }
        });
        $("input").keyup(function(e){
            trackId = $(this).attr('id');
            trackInputs[trackId] = $(this).val(); //Update trackInputs property with the value of the field with each keyup.
        });
    } 

Upvotes: 2

eug
eug

Reputation: 1158

I've finally found success using a textarea. For a password field there's an event handler that replaces each character typed with a "•".

Upvotes: 7

EngineerCoder
EngineerCoder

Reputation: 1455

The autocomplete feature has successfully disabled via this trick. It Works!

[HTML]

<div id="login_screen" style="min-height: 45px;">
   <input id="password_1" type="text" name="password">
</div>

[JQuery]

$("#login_screen").on('keyup keydown mousedown', '#password_1', function (e) {
    let elem = $(this);

    if (elem.val().length > 0 && elem.attr("type") === "text") {
        elem.attr("type", "password");
    } else {
        setTimeout(function () {
            if (elem.val().length === 0) {
                elem.attr("type", "text");
                elem.hide();
                setTimeout(function () {
                    elem.show().focus();
                }, 1);
            }
        }, 1);
    }

    if (elem.val() === "" && e.type === "mousedown") {
        elem.hide();
        setTimeout(function () {
            elem.show().focus();
        }, 1);
    }

});

Upvotes: 1

Edvard &#197;kerberg
Edvard &#197;kerberg

Reputation: 2191

This is the most recent solution that I have used.

$('#email').prop('autocomplete', true);

Upvotes: -7

lufc
lufc

Reputation: 2040

My workaround since none of the above appear to work in Chrome 63 and beyond

I fixed this on my site by replacing the offending input element with

<p class="input" contenteditable="true">&nbsp;</p>

and using jQuery to populate a hidden field prior to submission.

But this is a truly awful hack made necessary by a bad decision at Chromium.

Upvotes: 3

Karan Vyas
Karan Vyas

Reputation: 129

For Angular users :

Since the autocomplete = 'off' ignore by new chrome versions, chrome developer suggests autocomplete= 'false | random-string', so the google chrome/modern browsers have 2 type of users helpers -

  1. autocomplete='off' (which prevents last cached suggestions).
  2. autocomplete = 'false | random-string' (which prevents autofill setting, since the 'random-string' is not known by the browser).

so what to do, in case of disabling both the annoying suggestions? Here is the trick:-

  1. add autocomplete = 'off' in every input fields. (or simple Jquery).

Example : $("input").attr('autocomplete', 'off');

  1. Remove the <form name='form-name'> tag from HTML code and add ng-form = 'form-name' in your <div> container. Adding ng-form="form-name" will also retain all your validations.

Upvotes: 1

Iwan Ross
Iwan Ross

Reputation: 354

What I have done it to change the input type="text" to a multi line input ie.

 overflow-x:hidden;
 overflow-y:hidden;
 vertical-align:middle;
 resize: none;

A quick explanation of the code: The overflow-x and -y hidden wil disable the scroll buttons on the right of the textarea box. The vertial algin will align the lable vertical middle with the text area and the resize: none will disable the resize grabber at the bottom right of the textarea.

In essance it means that your textarea will appear like a textbox, but with chrome autofill off.

Upvotes: 0

Denis Brezhitskiy
Denis Brezhitskiy

Reputation: 424

In some cases, the browser will keep suggesting autocompletion values even if the autocomplete attribute is set to off. This unexpected behavior can be quite puzzling for developers. The trick to really forcing the no-autocompletion is to assign a random string to the attribute, for example:

autocomplete="nope"

Upvotes: 17

Stiffels
Stiffels

Reputation: 395

Use css text-security: disc without using type=password.

html

<input type='text' name='user' autocomplete='off' />
<input type='text' name='pass' autocomplete='off' class='secure' />

or

<form autocomplete='off'>
    <input type='text' name='user' />
    <input type='text' name='pass' class='secure' />
</form>

css

input.secure {
    text-security: disc;
    -webkit-text-security: disc;
}

Upvotes: 22

w3jimmy
w3jimmy

Reputation: 712

Pure HTML solution:

(No javascript needed, no css needed and no hidden inputs needed)

<form autoComplete="new-password" ... >
        <input name="myInput" type="text" autoComplete="off" id="myInput" placeholder="Search field" />
</form>

Notes:

  • form does not necessarily need to be the direct parent of the input element
  • input needs a name attribute

Upvotes: 1

I've tried all the mentioned advises but none of them worked. I'm using a google places autocomplete on the specifik input, and it is quite ugly if there is a google chrome autofill above the google places autocomplete list. Even setting autocomplete="anything" is useless because the autocomplete plugin itself setf this attr to "off" and it is totally ignored by chrome.

so my sollution is:

var fixAutocomplete = window.setInterval(function(){
    if ($('#myinput').attr('autocomplete') === 'false') {
        window.clearInterval(fixAutocomplete);  
    }

    $('#myinput').attr('autocomplete', 'false');
}, 500);

Upvotes: 0

frin
frin

Reputation: 4536

My problem was that Chrome would autofill postal code, over the Bootstrap autocomplete interface as I was auto suggesting possible values from my database.

Things I had to do:

  • Change input field's id property to something other than "postcode"
  • Change input field's autocomplete value to false
  • After calling $('#postcode_field').autocomplete(...) I had to reset the autocomplete property with $('#postcode_field').prop('autocomplete', 'false'); because Boostrap's autocomplete plugin changes it to off automatically.

Upvotes: 0

MagicSux
MagicSux

Reputation: 382

Well since we all have this problem I invested some time to write a working jQuery extension for this issue. Google has to follow html markup, not we follow Google

(function ($) {

"use strict";

$.fn.autoCompleteFix = function(opt) {
    var ro = 'readonly', settings = $.extend({
        attribute : 'autocomplete',
        trigger : {
            disable : ["off"],
            enable : ["on"]
        },
        focus : function() {
            $(this).removeAttr(ro);
        },
        force : false
    }, opt);

    $(this).each(function(i, el) {
        el = $(el);

        if(el.is('form')) {
            var force = (-1 !== $.inArray(el.attr(settings.attribute), settings.trigger.disable))
            el.find('input').autoCompleteFix({force:force});
        } else {
            var disabled = -1 !== $.inArray(el.attr(settings.attribute), settings.trigger.disable);
            var enabled = -1 !== $.inArray(el.attr(settings.attribute), settings.trigger.enable);
            if (settings.force && !enabled || disabled)
                el.attr(ro, ro).focus(settings.focus).val("");
        }
    });
};
})(jQuery);

Just add this to a file like /js/jquery.extends.js and include it past jQuery. Apply it to each form elements on load of the document like this:

$(function() {
    $('form').autoCompleteFix();
});

jsfiddle with tests

Upvotes: 7

coder9
coder9

Reputation: 1549

None of the solutions worked for me. Finally, after pulling my hair out for many hours I came up with this solution for ReactJS.

Tested on FireFox 54.0.1, Chrome 61.0.3163.100, Mac OS 10.13

I keep the type="text" and change it to relevant type on onChange event.

ex: HTML:

<input type="text" onChange={this.setAttributes} placeholder="Email" />

JS:

setAttr2: function(e){
    var value = e.target.value;
    if(value.length){
      e.target.setAttribute('type', 'email')
    } else {
      e.target.setAttribute('type', 'text')
    }
  }

Upvotes: 0

alehro
alehro

Reputation: 2208

Answer of Jobin Jose gave me a start. Here is what works for me:

<input type="password" name="password" id="password_fake" style="display:none;" />
<input type="password" name="password"/>

Be sure to not have autocomplete="off", which spoils the solution.

Upvotes: 0

Rikku121
Rikku121

Reputation: 2642

In case display: none doesn't work this is also possible and it seems to be working (Chrome v60.0.3112.113):

.hidden-fields {
    opacity: 0;
    float: left;
    height: 0px;
    width: 0px;
}

<input type="text" name="username" class="hidden-fields"> 
<input type="password" name="password" class="hidden-fields">

<your actual login fields></your actual login fields>

Upvotes: 1

Jeffrey Holmes
Jeffrey Holmes

Reputation: 367

Boom, Google Chrome and anyone else try defeat this then.

I was able to get this implemented today 7th September 2017, but using a FormCollection of random strings that generated in my MVC View.

I would first get a new random key in my index controller of my login page , encrypt and create a new totally unique random string (i actually used a 256 bit cypher to perform this, and a unique cypher and authentication key), i then append plain text 'Username' and 'Password' on the end of each string to later help me identify from the repsonding view controller the username and password. You could also change that plain string to anything as long as you know the pattern and it's unique.

In my view, I then used these variables appropriately and then in the responding controller - searched through a FormCollection and found my matching variables - and then used the Key-Value of that item as the corresponding Username and Password to process appropriately.

The other issue i had which i think is sneaky of Chrome, is that any

Any thoughts ?

<style>
    @@font-face {
      font-family: 'password';
      font-style: normal;
      font-weight: 400;
      src: url(https://jsbin-user-assets.s3.amazonaws.com/rafaelcastrocouto/password.ttf);
    }
</style>

<input type="text" name="@Model.UsernameRandomNameString" />
<input style="font-family: 'password'" type="text" name="@Model.PasswordRandomNameString" />

LogOnModel model = new LogOnModel()
            {
                UsernameRandomNameString = Cryptography.SimpleEncrypt("Username", UniqueGeneratorKey, UniqueGeneratorKey) + "Username",
                PasswordRandomNameString = Cryptography.SimpleEncrypt("Password", UniqueGeneratorKey, UniqueGeneratorKey) + "Password",
            };

I think it a hell of a workaround, but hey it works, and i think it could also be future proof unless google determines the URL of the page has key words in it, then appropriately just adds its stupid extensions on top on any input field - but that's a little drastic.

Upvotes: 1

J0ANMM
J0ANMM

Reputation: 8525

None of the other solutions to these question worked for me.

The only think that worked is this one:

It removes "name" and "id" attributes from elements and assigns them back after 1ms. Put this in document get ready.

$(document).ready(function() {
    $('form[autocomplete="off"] input, input[autocomplete="off"]').each(function () {

                var input = this;
                var name = $(input).attr('name');
                var id = $(input).attr('id');

                $(input).removeAttr('name');
                $(input).removeAttr('id');

                setTimeout(function () {
                    $(input).attr('name', name);
                    $(input).attr('id', id);
                }, 1);
            });
});

Upvotes: 0

Fstarocka Burns
Fstarocka Burns

Reputation: 163

I finally solved this by putting in a non duplicate variable in the input field - i used php time() like this:

<input type="text" name="town['.time().']" >

This was interfering mostly n android. All i did on the server side was to do a foreach loop on the input name - the issue is if chrome recognizes the name attribute it WILL auto populate.

Nothing else even worked for me.

Upvotes: -1

Kuf
Kuf

Reputation: 17818

For me, simple

<form autocomplete="off" role="presentation">

Did it.

Tested on multiple versions, last try was on 56.0.2924.87

Upvotes: 58

rybo111
rybo111

Reputation: 12588

Here are my proposed solutions, since Google are insisting on overriding every work-around that people seem to make.

Option 1 - select all text on click

Set the values of the inputs to an example for your user (e.g. [email protected]), or the label of the field (e.g. Email) and add a class called focus-select to your inputs:

<input type="text" name="email" class="focus-select" value="[email protected]">
<input type="password" name="password" class="focus-select" value="password">

And here's the jQuery:

$(document).on('click', '.focus-select', function(){
  $(this).select();
});

I really can't see Chrome ever messing with values. That'd be crazy. So hopefully this is a safe solution.

Option 2 - set the email value to a space, then delete it

Assuming you have two inputs, such as email and password, set the value of the email field to " " (a space) and add the attribute/value autocomplete="off", then clear this with JavaScript. You can leave the password value empty.

If the user doesn't have JavaScript for some reason, ensure you trim their input server-side (you probably should be anyway), in case they don't delete the space.

Here's the jQuery:

$(document).ready(function() {
  setTimeout(function(){
    $('[autocomplete=off]').val('');
  }, 15);
});

I set a timeout to 15 because 5 seemed to work occasionally in my tests, so trebling this number seems like a safe bet.

Failing to set the initial value to a space results in Chrome leaving the input as yellow, as if it has auto-filled it.

Option 3 - hidden inputs

Put this at the beginning of the form:

<!-- Avoid Chrome autofill -->
<input name="email" class="hide">

CSS:

.hide{ display:none; }

Ensure you keep the HTML note so that your other developers don't delete it! Also ensure the name of the hidden input is relevant.

Upvotes: 20

tutak
tutak

Reputation: 1098

If you are using Symfony forms, autocomplete=off will not work IF the attribute is applied from the twig template rather than using FormBuilder.

Use this:

....
->add('field-name', TextType::class, array(
  'attr' => array(
      'autocomplete' => 'off'
  )
)
....

Rather than:

....
{{ form_widget(form.field-name, {'attr': {'autocomplete':'off'}})
....

Upvotes: 0

Related Questions