Search code examples
javascriptiosautocompleteshortcutqueryselectall

Autofill username and password using queryselector by id


I’m trying to create some simple javascript to autofill a webpage.

I’d like to modify the following for use with a specific elementid for the username ‘password_username’ and password ‘password_password’

var result = [];

// Get all links from the page need to change to specific for username

var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "username";
}

// Get all links from the page need to change to specific for password

var elements = document.querySelectorAll("input");
for (let element of elements) {
element.value = "password";
}

// Call completion to finish
completion(result) `

I’ve only just started to learn code and have very basic javascript knowledge, any help is appreciated!

Cheers,

Mat


Solution

  • Not entirely sure if this will work as imagined as I can't test it out right now, but give it a shot:

    const usernameElements = document.querySelectorAll(`input[type="text"]`);
    const passwordElements = document.querySelectorAll(`input[type="password"]`);
    
    usernameElements.forEach(username => username.value = "the user name");
    passwordElements.forEach(password => password.value = "the password");
    

    It selects the input fields according to the type (text/password) and adds the value to them. Now I am not entirely sure if this that you posted is part of a bigger script, but this might do the trick that you need. You'd need to make the username and password variables to dynamically load, if you want different usernames and passwords, otherwise this adds the values that you give it, like for example username.value = "testing username" and password.value = "testing password" . Cheers.