ChatGPT解决这个技术问题 Extra ChatGPT

Override browser form-filling and input highlighting with HTML/CSS

I have 2 basic forms: sign in and sign up, both on the same page. Now, I have no problem with the sign in form auto-filling, but the sign up form auto fills as well, and I don't like it.

Also, the form styles get a yellow background which I can't manage to override and I don't want to use inline CSS to do so. What can I do to make them stop being colored yellow and (possibly) auto filling ?

You're really asking two questions here: How to disable form autofill? -AND- How to override yellow background when form autofill is enabled? This wasn't clear until I read all the comments in the answers below. You might want to consider editing your question (especially since you've gone as far as to offer a bounty).
You're right, edited. Or a lazy version of it anyways.
As a user of the form, I'd hate to have my usability crippled because of your visual preferences by forcing auto complete and highlighting off. Let the user turn this off, not you. Leave my browsing experience alone.
That's the thing, I only disabled autocomplete in the REGISTRATION form, which basically, shouldn't have regular autocomplete, the completion info is only created once you've signed up. As for the login form, I want to keep autocomplete on, but just disable the dumb color it puts on the input fields because the text inside becomes unreadable -- the background is yellow and the text color is white (original background is dark gray).

P
Pamela Joslyn

Trick it with a "strong" inside shadow:

input:-webkit-autofill {
    -webkit-box-shadow:0 0 0 50px white inset; /* Change the color to your own background color */
    -webkit-text-fill-color: #333;
}

input:-webkit-autofill:focus {
    -webkit-box-shadow: 0 0 0 50px white inset;/*your box-shadow*/
    -webkit-text-fill-color: #333;
} 

+1000 (if I could) Yeah I can't figure any other way to do this. This is really intrusive of webkit...
This is absolutely amazing, very creative solution, +allthepoints
awesome this should be the number one answer, simple and effective
This is awesome in that it works and is really creative. But it reminds me of old IE6 hacks and the like. Kinda crappy of google to give us a :-webkit-autofill parameter and not let designers override the default, right?
Providing a color choice that cannot be customised isn't helping usability, nor accessibility. Those concerns are still entirely in the hands of the dev, except for this frustrating hack in Chrome. No-one can fault the intention of the Chrome devs, just the results.
M
Mr_Green

for the autocompletion, you can use:

<form autocomplete="off">

regarding the coloring-problem:

from your screenshot i can see that webkit generates the following style:

input:-webkit-autofill {
    background-color: #FAFFBD !important;
}

1) as #id-styles are even more important than .class styles, the following may work:

#inputId:-webkit-autofill {
    background-color: white !important;
}

2) if that won't work, you can try to set the style via javascript programmatically

$("input[type='text']").bind('focus', function() {
   $(this).css('background-color', 'white');
});

3) if that won't work, you're doomed :-) consider this: this wont hide the yellow color, but will make the text readable again.

input:-webkit-autofill {
        color: #2a2a2a !important; 
    }

4) a css/javascript solution:

css:

input:focus {
    background-position: 0 0;
}

and the following javascript has to be run onload:

function loadPage()
{
    if (document.login)//if the form login exists, focus:
    {
        document.login.name.focus();//the username input
        document.login.pass.focus();//the password input
        document.login.login.focus();//the login button (submitbutton)
    }
}

eg:

<body onload="loadPage();">

good luck :-)

5) If none of the above work try removing the input elements, cloning them, then placing the cloned elements back on the page (works on Safari 6.0.3):

<script>
function loadPage(){

    var e = document.getElementById('id_email');
    var ep = e.parentNode;
    ep.removeChild(e);
    var e2 = e.cloneNode();
    ep.appendChild(e2);

    var p = document.getElementById('id_password');
    var pp = p.parentNode;
    pp.removeChild(p);
    var p2 = p.cloneNode();
    pp.appendChild(p2);
}

document.body.onload = loadPage;
</script>

6) From here:

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);
        });
    });
}

(1) doesn't work. I'll try (2) when I get back home; hopefully JS can override this; thanks :)
(4) definitely removes yellow :focus border.
If the last bit does not work for you, and you do know how javascript works (got the Id's right etc.) You could have the issue I had, I'm using jquery mobile for some reasons and this inits later and replaces the inputs it seems. So what I did is set an interval which clones it every 50 ms (it worked after 400ms using setTimeout but I don't want to risk slow connections). And after a second the interval is removed: code
var keepTheInputCloned = setInterval(function(){ var e = document.getElementById('id_email'); var ep = e.parentNode; ep.removeChild(e); var e2 = e.cloneNode(); ep.appendChild(e2); var p = document.getElementById('id_password'); var pp = p.parentNode; pp.removeChild(p); var p2 = p.cloneNode(); pp.appendChild(p2); },50); setTimeout(function(){clearInterval(keepTheInputCloned)},1000);
I'm having a similar problem with Safari on Mavericks. But when I employ method 5, they duke it out for one second (or three seconds when I set the timeout to 3000) and then the browser wins and I've got autocomplete turned on. In my usage case, I'm asking the user for their username/password for another site so that I can pull info from the other site, so I definitely don't want it autofilling the username and password they use for my site. Any thoughts on this (besides the doom of the original #3)?
M
MCBL

Add this CSS rule, and yellow background color will disapear. :)

input:-webkit-autofill {
    -webkit-box-shadow: 0 0 0px 1000px white inset;
}

This worked for me - thanks! (though I needed to change white to the color I actually wanted)
Clearly the best answer.
r
rav_kr

After 2 hours of searching it seems Google Chrome still overrides the yellow color somehow, but I found the fix. It will work for hover, focus etc. as well. All you have to do is to add !important to it.

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    -webkit-box-shadow: 0 0 0px 1000px white inset !important;
}

this will completely remove yellow color from input fields


It works for me without the 1000px, just 0 everywhere, -webkit-box-shadow: 0 0 0 0 white inset !important;
J
Jason Kester
<form autocomplete="off">

Pretty much all modern browsers will respect that.


Awesome, but it only solves the less important issue; how can I keep auto complete but lose the style ( prntscr.com/4hkh ) webkit shoves down its throat? o: thanks though
Actually, it should do both. The box only turns yellow to let you know that chrome/safari/ff has autofilled it with your password. If you tell it not to fill, it won't get a chance to color it in.
yes, but look at what I said: "how can I keep auto complete but lose the style webkit shoves"
Only problem with autocomplete is that it’s invalid in HTML before version 5.
K
Kerry7777

This seems to be working for me:

input { -webkit-background-clip: text !important; }


This is the only solution in case you want to have a transparent background
@Kerry7777 This is the only solution worked for me. And it's the simplest one. You made my day
a
andstud.io

Sometimes autocomplete on the browser still autocompletes when you just have the code in the <form> element.

I tried putting it in the <input> element as well and it worked better.

<form autocomplete="off">  AND  <input autocomplete="off">

Support for this attribute however is ceasing, please read https://bugzilla.mozilla.org/show_bug.cgi?id=956906#c1

https://bugzilla.mozilla.org/show_bug.cgi?id=956906

Another work around that I've found is taking out placeholders inside of the input fields that suggest that it is an email, username, or phone field (ie. "Your Email", "Email", etc.")

https://i.stack.imgur.com/3WE5U.png

This makes it so that browsers don't know what kind of field it is, thus doesn't try to autocomplete it.


What I like about this is most people WOULDN'T appreciate the whole form not being filled in on a page reload (e.g. a long text area), but allows the developer to prevent certain elements from being filled in (e.g. bank card number). Annoyingly though, support for this attribute is ceasing
D
Dmitriy Likhten

You can also change the name attribute of your form elements to be something generated so that the browser won't keep track of it. HOWEVER firefox 2.x+ and google chrome seems to not have much problems with that if the request url is identical. Try basically adding a salt request param and a salt field name for the sign-up form.

However I think autocomplete="off" is still top solution :)


A
Alan Plum

You can disable auto-completion as of HTML5 (via autocomplete="off"), but you CAN'T override the browser's highlighting. You could try messing with ::selection in CSS (most browsers require a vendor prefix for that to work), but that probably won't help you either.

Unless the browser vendor specifically implemented a vendor-specific way of overriding it, you can't do anything about such styles that are already intended to override the site's stylesheet for the user. These are usually applied after your stylesheets are applied and ignore ! important overrides, too.


A
Arjan

This fixes the problem on both Safari and Chrome

if(navigator.userAgent.toLowerCase().indexOf("chrome") >= 0 || navigator.userAgent.toLowerCase().indexOf("safari") >= 0){
window.setInterval(function(){
    $('input:-webkit-autofill').each(function(){
        var clone = $(this).clone(true, true);
        $(this).after(clone).remove();
    });
}, 20);
}

I believe it will but wouldn't it be a bit harsh to do this 50 times each second? I know it'll work and won't be too slow. But seems a bit too much.
z
zneak

The form element has an autocomplete attribute that you can set to off. As of the CSS the !important directive after a property keeps it from being overriden:

background-color: white !important;

Only IE6 doesn't understand it.

If I misunderstood you, there's also the outline property that you could find useful.


Chrome seems to ignore the !important when it autofills input-fields
@Torandi It might be because of the user-agent stylesheets. Settings from user-agent stylesheets should apply last, unless it has the !important directive, in which case it takes precedence over everything else. You should check out your user agent stylesheet (though I don't know where to find it).
w
whitehorse

If it's in input field you're trying to "un-yellow" ...

Set a background-color with css... let's say #ccc (light gray). Add value="sometext", which temporary fills the field with "sometext" (optional) Add a little javascript to make the "sometext" clear when you go to put the real text in.

So, it might look like this:

<input id="login" style="background-color: #ccc;" value="username"
    onblur="if(this.value=='') this.value='username';" 
    onfocus="if(this.value=='username') this.value='';" />

w
warfish

Lets use a little css hack:

input:-webkit-autofill, 
input:-webkit-autofill:hover, 
input:-webkit-autofill:focus, 
textarea:-webkit-autofill, 
textarea:-webkit-autofill:hover, 
textarea:-webkit-autofill:focus, 
select:-webkit-autofill, 
select:-webkit-autofill:hover, 
select:-webkit-autofill:focus, 
input:-internal-autofill-selected {
    -webkit-text-fill-color: #000;
    background: #fff !important;
    box-shadow: inset 0 0 0 1px rgb(255 255 255 / 0%), inset 0 0 0 100px #fff;
}

T
Thales Kenne

I was able to remove the autofill color with this approach:

  // Workaround to remove autofill color from inputs
  input, select {
    color: #fff !important;
    -webkit-text-fill-color: #fff !important;
    -webkit-background-clip: text !important;
    background-clip:  text !important;
  }

This is working for Safari and Chrome on iOS and Chrome on android, as far as I have tested.


A
Ananay Gupta

The accepted answer might have been a good answer for specific cases, but I was using angular material with transparent backgrounds and on top of that the field was not the 'entre material field' with the fancy borders etc.

I made this modified solution, that just forces a very long transition on any of the autofill pseudo-elements, so that the change in properties is not even noticeable unless the user manages to stay on the same page for a considerable amount of the 1000000000 or so seconds that I have set it to!

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
textarea:-webkit-autofill,
textarea:-webkit-autofill:hover,
textarea:-webkit-autofill:focus,
select:-webkit-autofill,
select:-webkit-autofill:hover,
select:-webkit-autofill:focus {
  transition: all 10000000s;
}

b
benzado

The screenshot you linked to says that WebKit is using the selector input:-webkit-autofill for those elements. Have you tried putting this in your CSS?

input:-webkit-autofill {
    background-color: white !important;
}

If that doesn't work, then nothing probably will. Those fields are highlighted to alert the user that they have been autofilled with private information (such as the user's home address) and it could be argued that allowing a page to hide that is allowing a security risk.


A
Adam

I've seen Google toolbar's autocomplete feature disabled with javascript. It might work with some other autofill tools; I don't know if it'll help with browsers built in autocomplete.

<script type="text/javascript"><!--
  if(window.attachEvent)
    window.attachEvent("onload",setListeners);

  function setListeners(){
    inputList = document.getElementsByTagName("INPUT");
    for(i=0;i<inputList.length;i++){
      inputList[i].attachEvent("onpropertychange",restoreStyles);
      inputList[i].style.backgroundColor = "";
    }
    selectList = document.getElementsByTagName("SELECT");
    for(i=0;i<selectList.length;i++){
      selectList[i].attachEvent("onpropertychange",restoreStyles);
      selectList[i].style.backgroundColor = "";
    }
  }

  function restoreStyles(){
    if(event.srcElement.style.backgroundColor != "")
      event.srcElement.style.backgroundColor = "";
  }//-->
</script>

E
Ernests Karlsons

After trying a lot of things, I found working solutions that nuked the autofilled fields and replaced them with duplicated. Not to loose attached events, i came up with another (a bit lengthy) solution.

At each "input" event it swiftly attaches "change" events to all involved inputs. It tests if they have been autofilled. If yes, then dispatch a new text event that will trick the browser to think that the value has been changed by the user, thus allowing to remove the yellow background.

var initialFocusedElement = null
  , $inputs = $('input[type="text"]');

var removeAutofillStyle = function() {
  if($(this).is(':-webkit-autofill')) {
    var val = this.value;

    // Remove change event, we won't need it until next "input" event.
    $(this).off('change');

    // Dispatch a text event on the input field to trick the browser
    this.focus();
    event = document.createEvent('TextEvent');
    event.initTextEvent('textInput', true, true, window, '*');
    this.dispatchEvent(event);

    // Now the value has an asterisk appended, so restore it to the original
    this.value = val;

    // Always turn focus back to the element that received 
    // input that caused autofill
    initialFocusedElement.focus();
  }
};

var onChange = function() {
  // Testing if element has been autofilled doesn't 
  // work directly on change event.
  var self = this;
  setTimeout(function() {
    removeAutofillStyle.call(self);
  }, 1);
};

$inputs.on('input', function() {
  if(this === document.activeElement) {
    initialFocusedElement = this;

    // Autofilling will cause "change" event to be 
    // fired, so look for it
    $inputs.on('change', onChange);
  }
});

M
Mite

Simple javascript solution for all browser:

setTimeout(function() {
    $(".parent input").each(function(){
        parent = $(this).parents(".parent");
        $(this).clone().appendTo(parent);   
        $(this).attr("id","").attr("name","").hide();
    }); 
}, 300 );

Clone input, reset attribute and hide original input. Timeout is needed for iPad


K
Kt Mack

Since the browser searches for password type fields, another workaround is to include a hidden field at the beginning of your form:

<!-- unused field to stop browsers from overriding form style -->
<input type='password' style = 'display:none' />

T
TwystO

I've read so many threads and try so many pieces of code. After gathering all that stuff, the only way I found to cleanly empty the login and password fields and reset their background to white was the following :

$(window).load(function() {
    setTimeout(function() {
        $('input:-webkit-autofill')
            .val('')
            .css('-webkit-box-shadow', '0 0 0px 1000px white inset')
            .attr('readonly', true)
            .removeAttr('readonly')
        ;
    }, 50);
});

Feel free to comment, I'm opened to all enhancements if you find some.


v
volodymyr3131

Autocomplete off is not supported by modern browsers. The easiest way to solve autocomplete I found was a little track with HTML and JS. The first thing to do is change the type of the input in HTML from 'password' to 'text'.

<input class="input input-xxl input-watery" type="text" name="password"/>

Autocomplete starts after window loaded. That's OK. But when the type of your field is not 'password', browser didn`t know what fields it must complete. So, there will be no autocomplete on form fields.

After that, bind event focusin to password field, for ex. in Backbone:

'focusin input[name=password]': 'onInputPasswordFocusIn',

In onInputPasswordFocusIn, just change the type of your field to password, by simple check:

if (e.currentTarget.value === '') {
    $(e.currentTarget).attr('type', 'password');
}

That`s it!

UPD: this thing doesn't work with disabled JavaSciprt

UPD in 2018. Also found some funny trick. Set readonly attribute to the input field, and remove it on the focus event. First prevent browser from autofilling fields, second will allow to input data.


Well autocomplete is part of the standard, though it's usage & implementation may vary. Also, changing input types in IE fails spectacularly, which is why jQuery blocks it, but generally it's not a good idea if you plan to support IE developer.mozilla.org/en-US/docs/Web/Security/…
@casraf Sorry, it is a part of standart, but it don't work in all modern browsers as it must, so it will not do the thing it was invented for. In EDGE it works fine, about previous versions can't tell anything(
True, it's not implemented everywhere. The problem still stands - depending on how far back you want to support IE - before v 11, I don't believe you can change the input type. If you're not worried about old versions, then you might as well use autocomplete=off, as it works in FF, Chrome for a while, and IE as of the previous version or so
I've tried to use autocomplete=off, both for inputs and form, and Chrome still fill signup and signin forms data(. This is just some kind of strange magic, because based on the comments, in some cases it works, and in some it does not =)
I know, these standards are not really being followed consistently. It's a shame, makes our lives harder :(
V
Vayodya Tamari

Please try with autocomplete="none" in your input tag

This works for me


Disabling "autocomplete" is not a good UX solution.
A
Andrei

I had to also change the text color to something darker (see StackOverflow dark theme colors).

So ended up with a hybrid of @Tamás Pap, @MCBL and @don's solution:

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    -webkit-box-shadow: 0 0 0px 1000px #2d2d2d inset !important;
    -webkit-text-stroke-color: #e7e8eb !important;
    -webkit-text-fill-color: #e7e8eb !important;
}

T
Tobias Buschor

You can style autofilled inputs using :-webkit-autofill

Even in firefox with the webkit-prefix!

To change the background color, there is the box-shadow trick.
And for Firefox you need additionally filter:none.

:-webkit-autofill { 
    filter:none; /* needed for firefox! */
    box-shadow: 0 0 0 100px rgba(38, 163, 48, 0.212) inset;
}

K
Kris

Why not just put this in your css:

input --webkit-autocomplete {
  color: inherit;
  background: inherit;
  border: inherit;
}

That should take care of your issue. Although it does raise a usability issue because now the user can't see that the form was autofilled in the way he/she is used to.

[edit] After posting this I saw that a similar answer was already given and that you commented on it that it didn't work. I don't quite see why because it did work when I tested it.


doesn't work in both chrome and safari. style is input:-webkit-autofill and input --webkit-autocomplete simply doesn't exist
@EliseuMonar: I'm pretty sure I wasn't lying, but can't remember details of how or where I tested it. The code itself was probably typed from memory, not copy/pasted, so autocomplete vs. autofill? I dunno.
P
Per Lindberg

The REAL problem here is that Webkit (Safari, Chrome, ...) has a bug. When there's more than one [form] on the page, each with an [input type="text" name="foo" ...] (i.e. with the same value for the attribute 'name'), then when the user returns to the page the autofill will be done in the input field of the FIRST [form] on the page, not in the [form] that was sent. The second time, the NEXT [form] will be autofilled, and so on. Only [form] with an input text field with the SAME name will be affected.

This should be reported to the Webkit developers.

Opera autofills the right [form].

Firefox and IE doesn't autofill.

So, I say again: this is a bug in Webkit.