Masking passwords with JavaScript

In this article, we'll explore a compact JavaScript snippet that generates a secure password, masks it for display, and provides a user-friendly way to copy it to the clipboard. This is particularly useful for web applications that deal with account creation or password management features.

Core Functionality Overview

The code centers around three primary tasks:

  1. Generating a random password with a customizable length
  2. Masking part of the password for safer on-screen display
  3. Allowing users to copy the full password to the clipboard

Password Generation

The generatePassword function creates a strong password by randomly selecting characters from a defined set that includes lowercase, uppercase, numbers, and symbols.


function generatePassword(length = 12) {
    const charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+';
    let password = '';
    for (let i = 0; i < length; i++) {
        let randomIndex = Math.floor(Math.random() * charset.length);
        password += charset[randomIndex];
    }
    return password;
}

This function defaults to a 12-character password, though the length can be customized. It ensures a high level of entropy by selecting characters from a diverse set.

Password Masking

To enhance user security, the generateMask function partially obscures the password, showing only the first four characters.


function generateMask(pass) {
    return pass.split('').map((char, index) => {
        return index < 4 ? char : '*';
    }).join('');
}

This approach is particularly helpful when displaying passwords in UI components, as it prevents full exposure while still allowing the user to recognize which password is in use.

Displaying and Copying the Password

The script selects two DOM elements: one to display the masked password, and another to handle the copy action.


const passwordText = document.querySelector('.password-text');
const passwordCopy = document.querySelector('.password-copy');

const password = generatePassword();
passwordText.textContent = generateMask(password);

The copy mechanism uses the navigator.clipboard.writeText API to securely place the full password into the user’s clipboard. Feedback is provided through dynamic button text updates.


passwordCopy.addEventListener('click', () => {
    passwordCopy.innerText = 'Copy password';
    navigator.clipboard.writeText(password).then(() => {
        passwordCopy.innerText = 'Password copied!';
        setTimeout(() => {
            passwordCopy.innerText = 'Copy password';
        }, 2000);
    }).catch(err => {
        passwordCopy.innerText = 'Failed to copy';
    });
});

Conclusion

This small yet effective script demonstrates how to build a user-friendly password utility for modern web applications. It combines security (through masking), usability (via clipboard integration), and simplicity, making it an excellent addition to any frontend toolkit.

Back to top