Would there be any way to detect login fields on ANY website using javascript? IE and Firefox have the ability to 'remember' my username and password. I would like to create a script that replicated that functionality. So for example, when presenting the login page for GMail, how could I 'find' the username and password field and get / set them?
Well one method (that I'm almost sure one of the browsers is using) would be to find the first <input type="password">, and then search for the <input type="text"> before it.
I think User/Password remember feature in browsers is triggered by a presence of a password-type input field in the form.
Next thing you'd have to do is to look for the most common login fields name
d 'login', 'user', 'username', 'j_username' (in case there's a JAAS-based site). If you don't, just store all text input fields. ;)
AFAIK, the IE and Firefox password detection stuff is based loosely on the name of the field, that is, it prompts you if you have the word username and/or password in the id.
if your using jQuery you could use something like.
$('input[id*=username]').css('background', 'red');
// or
$('input[id*=password]').css('background', 'red');
Additionally, you can check for any password fields using jQuery by
$(':password').css('background', 'red');
Basic outline:
- Gather all password fields
- Loop through all of them
- On each iteration:
- Find the <form/> that the password field is a part of
- Find the first input field in the form that is 1) not the password field and 2) not anything other than type="text"
- Return an array of all username/password pairs
Example output:
[ [ <input id="username" /> , <input type="password" id="pswd" /> ] ]
It will output an array of pairs, each pair contains a username and password node. Obviously, on most pages, you'll only get one pair because there's only one login section.
Here it is:
function getLoginFields() {
var fieldPairs = [],
pswd = (function(){
var inputs = document.getElementsByTagName('input'),
len = inputs.length,
ret = [];
while (len--) {
if (inputs[len].type === 'password') {
ret[ret.length] = inputs[len];
}
}
return ret;
})(),
pswdLength = pswd.length,
parentForm = function(elem) {
while (elem.parentNode) {
if(elem.parentNode.nodeName.toLowerCase() === 'form') {
return elem.parentNode;
}
elem = elem.parentNode;
}
};
while (pswdLength--) {
var curPswdField = pswd[pswdLength],
parentForm = parentForm(curPswdField),
curField = curPswdField;
if (parentForm) {
var inputs = parentForm.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i] !== curPswdField && inputs[i].type === 'text') {
fieldPairs[fieldPairs.length] = [inputs[i], curPswdField];
break;
}
}
}
}
return fieldPairs;
}
// Usage:
var loginFields = getLoginFields()[0]; // or loop through results.
Tested successfully on Yahoo, Amazon, Google, Youtube... (various account/login pages)