Is there any way to get value of an auto-filled password box in JavaScript?

3.3k Views Asked by At
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
    inputs[i].onfocus = foo;
}
function foo(){
    alert(this.value);
}

When the input values are manually entered:
Above code works and alerts the correct values regardless of the type of an input field.

When the input values auto-filled by browser:
Code works and alerts the correct values when the input field is of type text. In case of a password field, it alerts empty string!

Is this behaviour because of the browser's security policies? Or there's any workaround possible? I tried it in Chrome browser.

2

There are 2 best solutions below

2
On

This is an interesting question because I believe that you are referring to the side-effect of a security feature in Chrome.

Chrome (and probably other browsers) may not actually populate the DOM with the auto-filled password because a malicious programmer could write a JavaScript that attempts to steal auto-filled passwords from unsuspecting victims once a page loads.

You will most likely require that the user clicks a submit button before you can gain access to that information.

You might be able to force the form to submit and check the value right before the submit actually occurs. If that works, then you can just cancel the submission by returning false in "onsubmit" and you now have the password.

4
On
$(document).ready(function() {
  $("input")
      .blur(password)
      .trigger('blur');
});

function password() {
   alert($(this).val())
}

DEMO