When you have saved username and password for some site Chrome will autofill that username and password, but if you try to get the value for the password input field it is empty String even though there is value there ******.
If you click somewhere on the page no mater where the value of the input type="password" will be filled.
This is Fiddle user/pass of the structure of the html and the console.log command. It cannot be seen here but it can be reproduced on every page that has login form and the username and password are autofilled on the load of the page. If you inspect the value of the field before clicking anywhere else on the site it will be empty String.
This is not the case in Firefox or Internet Explorer it will fill the value of the input element with the password.
I am using Windows 7 Ultimate 64-bit OS and Google Chrome version is 48.0.2564.97 m
Is this normal behavior, bug or?
UPDATE:
If you click on F5 to reload the page and inspect the password field the value for password will be there. If you click the reload button in Chrome in top left corner the value for the password field will be empty string.
This seems to be a bug in Chrome. When Chrome auto-fills a password on an initial page load (but not a refresh), the value appears in the form field on-screen, but querying passwordField.value in Javascript returns an empty string. If you depend on seeing that value in Javascript, this prevents you from doing so. Once the user does any other action on the page, such as clicking anywhere on the page, the value suddenly becomes visible to Javascript.
I'm not actually 100% sure if this is a bug, or if there is a security reason for doing this such as preventing a hidden frame from stealing your password by tricking the browser into filling it in.
A workaround that we have used is to detect the background color change that Chrome makes to fields that it has auto-filled. Chrome colors the background of auto-filled fields yellow, and this change is always visible to Javascript even when the value is not. Detecting this in Javascript lets us know that the field was auto-filled with a value, even though we see the value as blank in Javascript. In our case, we have a login form where the submit button is not enabled until you fill in something in the password field, and detecting either a value or the auto-fill background-color is good enough to determine that something is in the field. We can then enable the submit button, and clicking the button (or pressing enter) instantly makes the password field value visible to Javascript because interacting with the page fixes the problem, so we can proceed normally from there.
Working Answer as of July 8, 2016
Adam correctly stated this is a bug (or intended behavior). However, none of the previous answers actually say how to fix this, so here is a method to force Chrome to treat the autocompleted value as a real value.
Several things need to happen in order, and this needs to only run in Chrome and not Firefox, hence the if.
First we focus on the element. We then create a new TextEvent, and run initTextEvent, which adds in a custom string that we specify (I used "#####") to the beginning of the value. This triggers Chrome to actually start acting like the value is real. We can then remove the custom string that we added, and then we unfocus.
Code:
input.focus();
var event = document.createEvent('TextEvent');
if ( event.initTextEvent ) {
event.initTextEvent('textInput', true, true, window, '#####');
input.dispatchEvent(event);
input.value = input.value.replace('#####','');
}
input.blur();
Edit August 10, 2016
This only works right now in Chrome on Windows and Android. Doesn't work on OSX. Additionally, it will stop working at all in Sept 2016, according to:
https://www.chromestatus.com/features/5718803933560832
Also, I've opened a Chromium ticket.
https://bugs.chromium.org/p/chromium/issues/detail?id=636425
As of August 12, a member of the Chrome team said on the above ticket that the behavior won't be changing because they don't consider it a bug.
Long-term Work-Around Suggestion:
That said, the current behavior has been tweaked from when it was first implemented. The user no longer has to interact with the password input for the value to be reported. The user now just needs to interact (send a mouse or keyboard event) with any part of the page. That means that while running validation on pageload still won't work, clicking on a submit button WILL cause Chrome to correctly report the password value. The work-around then, is to revalidate all inputs that might be autocompleted, if that is what you are trying to do, on submit.
Edit December 13, 2016:
A new Chromium ticket has been opened and is being received better. If interested in changing this behavior of Chrome's, please star this new ticket:
https://bugs.chromium.org/p/chromium/issues/detail?id=669724
Continuing from what Kelderic said, here's my work around. Like a lot of people, I don't need the actual password value. I really just need to know that the password box has been autofilled, so that I can display the proper validation messages.
Personally, I would not use suggested solution to detect the background color change cause by Chrome's autofill. That approach seems brittle. It depends on that yellow color never changing. But that could be changed by an extension and be different in another Blink based browser (ie. Opera). Plus, there's no promise Google wont use a different color in the future. My method works regardless of style.
First, in CSS I set the content of the INPUT when the -webkit-autofil pseudo-class is applied to it:
input:-webkit-autofill {
content: "\feff"
}
Then, I created a routine to check for the content to be set:
const autofillContent = `"${String.fromCharCode(0xFEFF)}"`;
function checkAutofill(input) {
if (!input.value) {
const style = window.getComputedStyle(input);
if (style.content !== autofillContent)
return false;
}
//the autofill was detected
input.classList.add('valid'); //replace this. do want you want to the input
return true;
}
Lastly, I polled the input to allow the autofill time to complete:
const input = document.querySelector("input[type=password]");
if (!checkAutofill(input)) {
let interval = 0;
const intervalId = setInterval(() => {
if (checkAutofill(input) || interval++ >= 20)
clearInterval(intervalId);
}, 100);
}
It is amazing that in 2021 this has not been solved in Chrome yet, I have had issue with autocomplete since 2014 and still nothing.
Chrome functionality autocomplete is misleading for the user, I do not know what are they trying to achieve but does not look good.
As it is now, form appears showing auto-completed text (user/email/pass) to the user, but in the background html - values are not inside of the elements.
As values are not in fields custom validation will disable submit button.
Script that checks fields values will say value is null, which is even more confusing for the user as s/he can see text is there, and can assume it is valid, leading to confusing delete-one insert one character. (Embarrassingly, I have to admit I did not know that you need to click in the body of the HTML, so I wonder how many users don not know the same)
In my case I wanted to have empty field always and then fount out it is just needlessly spent time to make it work.
If we try autocomplete=off we will discover that it is not working. And to validate fields and let say enable button we need to do some trickery.
(Have in mind that I have tried autocomplete=password new-password) and other type of Hocus-Pocus trickery from official resource.
At the end I have done this.
<script>
$('#user').value = ' '; //one space
$('#pass').value = ' '; // one space - if this is empty/null it will autopopulate regardless of on load event
window.addEventListener('load', () => {
$('#user').value = ''; // empty string
$('#pass').value = ''; // empty string
});
</script>
So, it will blink for a split second in some cases in password field with * not ideal but :/ ...
Here's my solution to this issue:
$(document).ready(function(){
if ( $("input:-webkit-autofill").length ){
$(".error").text("Chrome autofill detected. Please click anywhere.");
}
});
$(document).click(function(){
$(".error").text("");
});
Basically, clicking makes the input visible to the user, so I ask the user to click and when they do, I hide the message.
Not the most elegant solution but probably the quickest.
$(document).ready
does not wait for autofill of browser, it should be replaced by
$(window).on("load", checkforAutoFill())
Another option as of Dec. 16 / Chrome 54
I can't get the value of the password field, but, after "a short while", I can get the length of the password by selecting it, which is sufficient for me to enable the submit button.
setTimeout(function() {
// get the password field
var pwd = document.getElementById('pwd');
pwd.focus();
pwd.select();
var noChars = pwd.selectionEnd;
// move focus to username field for first-time visitors
document.getElementById('username').focus()
if (noChars > 0) {
document.getElementById('loginBtn').disabled = false;
}
}, 100);
The workaround specified by Adam:
... detect the background color change that Chrome makes to fields that it has auto-filled. Chrome colors the background of auto-filled fields yellow, and this change is always visible to Javascript even when the value is not. Detecting this in Javascript lets us know that the field was auto-filled with a value, even though we see the value as blank in Javascript
I did like this:-
getComputedStyle(element).backgroundColor === "rgb(250, 255, 189)"
where rgb(250, 255, 189) is the yellow color Chrome applies to auto filled inputs.
I have found a solution to this issue that works for my purposes at least.
I have a login form that I just want to hit enter on as soon as it loads but I was running into the password blank issue in Chrome.
The following seems to work, allowing the initial enter key to fail and retrying again once Chrome wakes up and provides the password value.
$(function(){
// bind form submit loginOnSubmit
$('#loginForm').submit(loginOnSubmit);
// submit form when enter pressed on username or password inputs
$('#username,#password').keydown(function(e) {
if (e.keyCode == 13) {
$('#loginForm').submit(e);
return false;
}
});
});
function loginOnSubmit(e, passwordRetry) {
// on submit check if password is blank, if so run this again in 100 milliseconds
// passwordRetry flag prevents an infinite loop
if(password.value == "" && passwordRetry != true)
{
setTimeout(function(){loginOnSubmit(e,true);},100);
return false;
}
// login logic here
}
Just wrote an angular directive related to this. Ended up with the following code:
if ('password' == $attrs.type) {
const _interval = $interval(() => { //interval required, chrome takes some time to autofill
if ($element.is(':-webkit-autofill')) { //jQuery.is()
//your code
$interval.cancel(_interval);
}
}, 500, 10); //0.5s, 10 times
}
ps: it wont detect 100% of the times, chrome might take longer than 5 seconds to fill the input.
Chrome's intended behavior is that an auto-filled password has an empty value in the DOM until the user interacts with the frame in some way, at which point chrome actually populates the value. Until this point any client side validation or attempt to ajax submit the form will see the password as empty.
This 'populate password value on frame interaction' behavior is inconsistent. I've found when the form is hosted in a same-origin iframe it only operates on the first load, and never on subsequent loads.
This is most evident on ajax forms where the autocomplete password populates on first load, however if that password is invalid and the ajax submission re-renders the form DOM, the autocompleted password re-appears visually but the value is never populated, irrespective of interaction.
None of the workarounds mentioned such as triggering blur or input events worked in this scenario. The only workaround I've found is to reset the password field value after the ajax process re-renders the form, e.g.:
$('input[type="password"]').val("");
After the above, Chrome actually autocompletes the password again but with the value actually populated.
In my current use case I'm using ASP.NET's Ajax.BeginForm and use the above workaround in the AjaxOptions.OnSuccess callback.
$element.is("*:-webkit-autofill")
works for me
With Angular, the new behaviour in Chrome (only allowing autofilled values to be read after the user has interaction with the page) manifests itself as an issue when you're using Angular's validation functionality in certain scenarios (for e.g using standard method/action attributes on the form). As the submit handler is executed immediately, it does not allow the form validators to capture the autofilled values from Chrome.
A solution I found for this to explicitly call the form controllers $commitViewValue function in the submit handler to trigger a revalidation before checking form.$valid or form.invalid etc.
Example:
function submit ($event) {
// Allow model to be updated by Chrome autofill
// #see http://stackoverflow.com/questions/35049555/chrome-autofill-autocomplete-no-value-for-password
$scope.loginModule.$commitViewValue();
if ($scope.loginModule.$invalid) {
// Disallow login
$scope.loginModule.$submitted = true;
$event.preventDefault();
} else {
// Allow login
}
}
Although this is working for us so far, I would be very interested if someone has found another, more elegant work around for the issue.
var txtInput = $(sTxt);
txtInput.focus();
txtInput.select();
This solution worked in my case.
Using jQuery 3.1.1.
If you want make input to be seen as fulfilled, try to trigger blur on it:
$('input[type="password"]').blur();
The autocomplete feature has successfully disabled.
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);
}
});
To me none of this solutions seemed to work.
I think this is worth mentioning that if you want to use it for CSS styling you sould use -webkit-autofill property like this:
input:-webkit-autofill~.label,
input:-webkit-autofill:hover~.label,
input:-webkit-autofill:focus~.label
input:focus~.label,
input:not(.empty)~.label {
top: -12px;
font-size: 12px;
color: rgba(0, 0, 0, .4);
font-weight: 600
}
My solution comparing my css to the chrome autocomplete color...
$('input, select, textarea').each(function(){
var inputValue = $(this).val();
if ( inputValue != "" || $(this).css("background-color") != "rgba(255, 255, 255, 0)") {
$(this).parents('.form-group').addClass('focused');
}
});
I tried all the solutions and wasn't working for me so i came up with this.
My problem is i have an input that move the placeholder top when it is filled, off course this is not working when Chrome autofill it.
Only tested in Chrome :
setTimeout(function () {
var autofilled = document.querySelectorAll('input:-webkit-autofill');
for (var i = 0; i < autofilled.length; i++) {
Do something with your input autofilled
}
}, 200);
My version is 95.0.4638.69
I'm facing a similar issue and I solved it by changing my form's name from "login-form" to another name which does not mean anything and solve it. Reason why I didn't remove name attribute is because if I remove name attribute Chrome will look up to id attribute and do the same thing.
Option using onanimationstart event (ReactJs) - Mar 22
I could avoid the needing of verifying periodically if the input was autofilled, as described above using setInterval, by taking advantage of the onanimationstart event. I don't know if it will work in every case, but definitely did the trick for me.
I'll provide a code sample in ReactJs, it may be explanatory enough to be transposed to another context.
First of all, is necessary to add in your input the onAnimationStart property, in such a way that the event is passed as parameter to your function, as following below.
<input
className={componentClass}
placeholder={placeholder}
onChange={handleChange}
onFocus={onFocus}
onMouseEnter={onHover}
onMouseLeave={onHover}
onBlur={onBlur}
disabled={disabled}
name={name}
value={value}
onAnimationStart={e => this.onAnimationStart(e)}
/>
Then let's proceed to the onAnimationStart function body.
onAnimationStart(event) {
// on autofill animation
if (event.animationName === 'onAutoFillStart') {
event.target?.labels[0].classList.add('grm-form__isAutofilled');
}
}
First I verified if the animation name was actually the auto-fill animation, and then I added a class to the first label of my input, this is my use case but can be adapted to solve different problems.
Just set the autocomplete attribute to username for the username field and new-password for the password field;
<input type="text" id="username" autocomplete="username">
<input type="password" id="password" autocomplete="new-password" >
You mentioned:
If you click somewhere on the page no matter where the value of the input type="password" will be filled.
Which is why I simply use $('body').click(); to simulate this first click, after which the value is available in JavaScript.
Also, I set autocomplete="new-password" on my signup form password field, so that the field is not autofilled and users have to fill in a new password.
See this Google Developers page for more information.
It's not a bug. It's a security issue. Imagine if one could just use javascript to retrieve autofilled passwords without the users' acknowledgment.
I have the following situation in a web application I am working on:
I have a form with a set of index field values that a user enters information into and then submits the form to the server. Field validation takes place on the server. If any field is found to be invalid, the form is redisplayed and I want to the input focus to automatically go to the first invalid field. I have the code in place to make it happen but the problem is that the focus is not being placed on the field in IE 10 (yet it is being placed in Firefox).
placefocusonfirstinvalidindexfield();
// After an attempt to upload has failed due to one or more invalid fields, then place the input focus automatically on the first
// invalid field:
function placefocusonfirstinvalidindexfield() {
var hasattemptedupload = '#Model.HasAttemptedUpLoadNumeric';
if (hasattemptedupload == 1) {
var indexfirstinvalidfield = '#Model.GetIndexOfFirstInvalidField()';
// focusIndexField(indexfirstinvalidfield);
setTimeout(focusIndexField(indexfirstinvalidfield), 100);
}
}
function focusIndexField(fieldindex) {
var control = document.getElementById("field" + fieldindex);
control.focus();
}
In the code above, I have confirmed that the correct field is being referenced. Everything appears to be as it should, except at the end of process, IE10 does not place the focus on the referenced field. Why not and what would I have to do to make that happen?
Just attempted this in the console to test in IE. The following code worked fine when testing focus on the "Post your answer" text area on this page.
setTimeout(function() { document.getElementById("wmd-input").focus() }, 5000);
Maybe there is something else in your code interfering with the focus? Have you tried extending the timeout value to see if it has something to do with that?
You are trying to haxx around the DOM loading with this row right?
setTimeout(focusIndexField(indexfirstinvalidfield), 100);
That row doesn't work as you expect. The focusIndexField is executed instantly and the response of the function is delayed 100 ms by the setTimeout function.
This would work as you expect:
setTimeout(function() {focusIndexField(indexfirstinvalidfield)}, 100);
However, it's not a good solution. The code should be executed when the document is ready instead.
Well, everything's in the title but I'll explain a little more :-)
My rails app contain many forms (Ajaxified or not).
To prevent users to submit twice or more some forms, I use Javascript.
There's my scenario for a Ajaxified form :
the user submit the form (clic or enter)
the javascript disable the submit button
the rails controller do things (like a Soap request or an insert in a DB)
the rails controller update the page and enable the submit button if necessary (in case of errors)
Now I want to add server side code to keeps things really clean if the user bypass the javascript.
Any suggestions?
You can add the option :disable_with => "Please Wait..." to the submit tag.
I use 4 method for 4 scenarios, please firstly prefer my awnser here: Prevent double submits in a Rails AJAX form
only click limitation for users:
use stopImmediatePropagation and add a click event to the target dom.
/**
* 防止按钮重复点击。
* NOTICE: #1 需要在作用点之前调用此方法 #2 stopImmediatePropagation 会阻止后面的所有事件包括事件冒泡
* #delay_duration 两次点击的间隔时间
*/
$.fn.preventMultipleClick = function (delay_duration) {
delay_duration = delay_duration || 3000;
var last_click_time_stamp = 0;
var time_duration = 0;
$(this).bind('click', function (event) {
time_duration = last_click_time_stamp ? event.timeStamp - last_click_time_stamp : 0;
//console.debug("preventMultipleClick", last_click_time_stamp, time_duration);
if (time_duration && time_duration < delay_duration) {
event.stopImmediatePropagation();
} else {
//console.debug("skip preventMultipleClick~");
last_click_time_stamp = event.timeStamp;
}
});
};
limit the submit such as ajax:
use ajax's beforeSend attribut.
/**
* 使用:
* 在jquery的ajax方法中加入参数:beforeSend
* 例如:beforeSend: function(){return $.preventMultipleAjax(event, 5000)}
*
* #param event
* #param delay_duration
* #returns {boolean}
*/
$.preventMultipleAjax = function (event, delay_duration) {
delay_duration = delay_duration || 3000;
var target = $(event.target);
var last_click_time_stamp = target.attr("_ajax_send_time_stamp") || 0;
var time_duration = last_click_time_stamp ? event.timeStamp - last_click_time_stamp : 0;
//console.debug("preventMultipleAjax", last_click_time_stamp, time_duration);
if (time_duration && time_duration < delay_duration) {
return false;
} else {
//console.debug("skip preventMultipleAjax~");
target.attr("_ajax_send_time_stamp", event.timeStamp);
return true;
}
};
only for form:
<%= f.submit "Save annotation", :disable_with => "Saving...", :class => "btn btn-primary", :id => "annotation-submit-button" %>
or:
disable:仅仅对表单元素,按钮等起作用,会阻止其上的事件触发
<input type="submit" value="submit" />
<input type="button" value="button" />
<input type="image" value="image" />
others:
This is the gem:https://github.com/mlanett/redis-lock
Redis.current.lock("#{current_user.id}.action_name") do
# Some code
end
Try using Redis locking and surround your block with something like
Redis.current.lock("#{current_user.id}.action_name") do
# Some code
end
This is the gem I'm using
https://github.com/mlanett/redis-lock
Here's what I'd do:
Add a "token" field to an object in db that's about to be changed.
Put that token into a form that modifies said object.
Right after modification save that object with NEW token.
Use that token in other page views.
This will not prevent double submission, but at least will prevent the changes from second commit. I.e. when user submits the form second time the code will check the submitted token against the one in database and if they do not match - do not do an update to the object.
This also has a draw back for newly created objects (i.e. if user want's to create a comment or smth like that). But in this case you may want to check the creation time interval from same user and if it's less than, say, 5 seconds - you'd prevent the object from being "created".
Not a real suggestion (I won't be surprised of downvotes), but will your site still be usable without JS? How about showing him appropriate message that for normal operation he needs to enable the JS, otherwise you won't show him lots and lots of forms on the page.
1) It's nice to also show some moving indicator to let user know that something's going on, that their request is being processed. It should eliminate lots of double submits.
2) If user has disabled javascript, how're you gonna submit 'ajaxified' forms? If site becomes not functional without javascript, then it's probably best to just notify user (like Eimantas suggests).
edit
One example of such indicator, just to be clear what I mean in 1.
http://www.netzgesta.de/busy/
Not sure if this is helpful:
ON SERVERSIDE:
On fresh load of the form,
set a session['variable']=false //meaning the form isn't submitted yet.
On form submit, check:
if session['variable'] == true
{
do nothing...
}
else
{
set session['variable'] = true;
//do submit logic here
}
I happen to face the same problem as well, and I have solved it with a very simple way(maybe it is not proper or it exists something buggy I didn't notice, please inform me if you found out)
Here is my answer:
$submitButton.on('click', function(e) {
setTimeout(() => {
$(this).attr('disabled', '');
}, 0);
});
The main issue I was facing was that if I double clicked my original button, it would submit request twice and caused something unpredictable, so I tried to block the button with "disabled"attribute right after clicking it. Here is what I wrote.
// !!this is an incorrect example!!
$submitButton.on('click', function(e) {
$(this).attr('disabled', '');
});
// !!don't copy this!!
The biggest problem I was facing is that if I just disable the submit button right after clicking it, the submit request won't submit and the page will just hang there, as nothing ever happens.
I think the cause is that the "disabled" attribute prevents the submit request from submitting.(Although I have no clue what the relationship between these two...)
So, I think the disable event should be executed after submit event.
As far as I understand, form submitting is a Javascript event, and setTimeout is an async method. As Javascript executes based on event loop, the ajax event will be put in the end of the event quene, and will be executed only after all the sync events finish.
In my code, after the first click, the submit button will be disabled after 0 millisecond, which is impossible for human beings to click the second time, problem solved!