How can I hide the password entered via a JavaScript dialog prompt?

Are you looking for the prompt function?

var response = prompt("What is your name?");

alert("Hello, " + response);

The dialog will look something like this:

enter image description here

This this probably isn't the best way to get password input, because it does not mask the input. Instead, consider using an HTML form with a password input field.


Maybe you are looking for basic HTTP authentication instead?

You can set this by getting your web server to send a few headers; for example with PHP:

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

This will cause the client to show a dialog like this:

enter image description here


You cannot mask the input with a JavaScript window.prompt()

Consider using a jQuery UI Modal Form Dialog.

http://jqueryui.com/dialog/#modal-form


There is currently no way to edit the prompt() function in JavaScript to make it hide the text input.

Instead, we need to create an popup in HTML and show it when needed. I've created a minimalist example here:

var promptCount = 0;
window.pw_prompt = function(options) {
    var lm = options.lm || "Password:",
        bm = options.bm || "Submit";
    if(!options.callback) { 
        alert("No callback function provided! Please provide one.") 
    };

    var prompt = document.createElement("div");
    prompt.className = "pw_prompt";

    var submit = function() {
        options.callback(input.value);
        document.body.removeChild(prompt);
    };

    var label = document.createElement("label");
    label.textContent = lm;
    label.for = "pw_prompt_input" + (++promptCount);
    prompt.appendChild(label);

    var input = document.createElement("input");
    input.id = "pw_prompt_input" + (promptCount);
    input.type = "password";
    input.addEventListener("keyup", function(e) {
        if (e.keyCode == 13) submit();
    }, false);
    prompt.appendChild(input);

    var button = document.createElement("button");
    button.textContent = bm;
    button.addEventListener("click", submit, false);
    prompt.appendChild(button);

    document.body.appendChild(prompt);
};

pw_prompt({
    lm:"Please enter your password:", 
    callback: function(password) {
        alert("Your password is: " + password);
    }
});

Most likely you want it to look like a popup, so I added some basic CSS to do so here:

.pw_prompt {
    position:fixed;
    left: 50%;
    top:50%;
    margin-left:-100px;
    padding:15px;
    width:200px;
    border:1px solid black;
}
.pw_prompt label {
    display:block; 
    margin-bottom:5px;
}
.pw_prompt input {
    margin-bottom:10px;
}

Altogether, you get this demo