可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
How can I hide the password entered by a user in a dialog prompt in JavaScript? For example, using something like
var passwd = prompt("Enter Password : ", "your password here");
I would like that when e.g. 12345
is entered, it appears like *****
or .....
in the dialog box.
Can anyone suggest how I can do this or provide some example code?
回答1:
Are you looking for the prompt
function?
var response = prompt("What is your name?");
alert("Hello, " + response);
The dialog will look something like this:
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:
回答2:
You cannot mask the input with a JavaScript window.prompt()
Consider using a jQuery UI Modal Form Dialog.
http://jqueryui.com/dialog/#modal-form
回答3:
You should use an input element with type password
in a form element:
<input name="myPass" id="myPass" type="password" />
回答4:
The only way to block the input of a password is to use <input type="password">
. Here's an example of how to make this a popup dialog:
/*
JavaScript Password Prompt by Luc (luc@ltdinteractive.com)
Originaly posted to http://stackoverflow.com/questions/9554987/how-can-i-hide-the-password-entered-via-a-javascript-dialog-prompt
This code is Public Domain :)
Syntax:
password_prompt(label_message, button_message, callback);
password_prompt(label_message, button_message, width, height, callback);
Example usage:
password_prompt("Please enter your password:", "Submit", function(password) {
alert("Your password is: " + password);
});
*/
window.password_prompt = function(label_message, button_message, arg3, arg4, arg5) {
if (typeof label_message !== "string") var label_message = "Password:";
if (typeof button_message !== "string") var button_message = "Submit";
if (typeof arg3 === "function") {
var callback = arg3;
}
else if (typeof arg3 === "number" && typeof arg4 === "number" && typeof arg5 === "function") {
var width = arg3;
var height = arg4;
var callback = arg5;
}
if (typeof width !== "number") var width = 200;
if (typeof height !== "number") var height = 100;
if (typeof callback !== "function") var callback = function(password){};
var submit = function() {
callback(input.value);
document.body.removeChild(div);
window.removeEventListener("resize", resize, false);
};
var resize = function() {
div.style.left = ((window.innerWidth / 2) - (width / 2)) + "px";
div.style.top = ((window.innerHeight / 2) - (height / 2)) + "px";
};
var div = document.createElement("div");
div.id = "password_prompt";
div.style.background = "white";
div.style.color = "black";
div.style.border = "1px solid black";
div.style.width = width + "px";
div.style.height = height + "px";
div.style.padding = "16px";
div.style.position = "fixed";
div.style.left = ((window.innerWidth / 2) - (width / 2)) + "px";
div.style.top = ((window.innerHeight / 2) - (height / 2)) + "px";
var label = document.createElement("label");
label.id = "password_prompt_label";
label.innerHTML = label_message;
label.for = "password_prompt_input";
div.appendChild(label);
div.appendChild(document.createElement("br"));
var input = document.createElement("input");
input.id = "password_prompt_input";
input.type = "password";
input.addEventListener("keyup", function(e) {
if (event.keyCode == 13) submit();
}, false);
div.appendChild(input);
div.appendChild(document.createElement("br"));
div.appendChild(document.createElement("br"));
var button = document.createElement("button");
button.innerHTML = button_message;
button.addEventListener("click", submit, false);
div.appendChild(button);
document.body.appendChild(div);
window.addEventListener("resize", resize, false);
};
回答5:
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
回答6:
A solution to me, builded up with the help of the above and the tutorial from http://bluebirdjs.com/docs/async-dialogs.html was to use an async function.
Because I wanted to replace the prompt and its logic. Unfortunately i could not find an easier solution, but this worked for me:
function passwordPrompt(text){
/*creates a password-prompt instead of a normal prompt*/
/* first the styling - could be made here or in a css-file. looks very silly now but its just a proof of concept so who cares */
var width=200;
var height=100;
var pwprompt = document.createElement("div"); //creates the div to be used as a prompt
pwprompt.id= "password_prompt"; //gives the prompt an id - not used in my example but good for styling with css-file
pwprompt.style.position = "fixed"; //make it fixed as we do not want to move it around
pwprompt.style.left = ((window.innerWidth / 2) - (width / 2)) + "px"; //let it apear in the middle of the page
pwprompt.style.top = ((window.innerWidth / 2) - (width / 2)) + "px"; //let it apear in the middle of the page
pwprompt.style.border = "1px solid black"; //give it a border
pwprompt.style.padding = "16px"; //give it some space
pwprompt.style.background = "white"; //give it some background so its not transparent
pwprompt.style.zIndex = 99999; //put it above everything else - just in case
var pwtext = document.createElement("div"); //create the div for the password-text
pwtext.innerHTML = text; //put inside the text
pwprompt.appendChild(pwtext); //append the text-div to the password-prompt
var pwinput = document.createElement("input"); //creates the password-input
pwinput.id = "password_id"; //give it some id - not really used in this example...
pwinput.type="password"; // makes the input of type password to not show plain-text
pwprompt.appendChild(pwinput); //append it to password-prompt
var pwokbutton = document.createElement("button"); //the ok button
pwokbutton.innerHTML = "ok";
var pwcancelb = document.createElement("button"); //the cancel-button
pwcancelb.innerHTML = "cancel";
pwprompt.appendChild(pwcancelb); //append cancel-button first
pwprompt.appendChild(pwokbutton); //append the ok-button
document.body.appendChild(pwprompt); //append the password-prompt so it gets visible
pwinput.focus(); //focus on the password-input-field so user does not need to click
/*now comes the magic: create and return a promise*/
return new Promise(function(resolve, reject) {
pwprompt.addEventListener('click', function handleButtonClicks(e) { //lets handle the buttons
if (e.target.tagName !== 'BUTTON') { return; } //nothing to do - user clicked somewhere else
pwprompt.removeEventListener('click', handleButtonClicks); //removes eventhandler on cancel or ok
if (e.target === pwokbutton) { //click on ok-button
resolve(pwinput.value); //return the value of the password
} else {
reject(new Error('User cancelled')); //return an error
}
document.body.removeChild(pwprompt); //as we are done clean up by removing the password-prompt
});
pwinput.addEventListener('keyup',function handleEnter(e){ //users dont like to click on buttons
if(e.keyCode == 13){ //if user enters "enter"-key on password-field
resolve(pwinput.value); //return password-value
document.body.removeChild(pwprompt); //clean up by removing the password-prompt
}else if(e.keyCode==27){ //user enters "Escape" on password-field
document.body.removeChild(pwprompt); //clean up the password-prompt
reject(new Error("User cancelled")); //return an error
}
});
});
}
now with this you can use the await inside an async-function to get nearly the same result as the window.prompt():
async function testThePrompt(){
var result = await passwordPrompt("please enter your password");
alert(result);
}
you see that this code nearly looks like the use of the old "prompt". The big difference is that we now use async-code - so the code does not stop executing while waiting for the password - just your async-function will wait till the password is either entered or . but for me it helped a lot to not rewrite my whole code anew just to handle the callback-function and stuff.
note that this only works in browsers which supports async, so from 2017 onward. old browsers like on older ipads or older versions of ios in general it will not work.
if you want to check for the event the user did not enter anything use
async function testThePrompt(){
var result;
try{
result = await passwordPrompt("please enter your password");
alert(result);
} catch(e){
alert("user canceled");
}
}
回答7:
I have tried to solve the same problem in the following way:
In the main page the user shall press a button in order to launch the request
pressing a button will open a popup windows by the JavaScript command window.open("password.html","passwordRequest",windowStyleVar)
,
where windowStyleVar
may be:
var windowStyleVar = "top=10, left=10, width=250, height=200, status=no,
menubar=no, toolbar=no scrollbars=no";
password.html looks like:
<html>
<head>
<title>Richiesta password</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function andiamo()
{
//pass the password to the main page "THeForm" form to <input type="hidden" name="vpassword" value="">
window.opener.document.getElementById('TheForm').vpassword.value=document.getElementById("picchio").value;
// launch the javascript function processRequest() in order to compare password and whatever You need in the main page
window.opener.processRequest();
window.close();
}
</script>
</head>
<body>
<div>type the password <input type="password" name="picchio" id="picchio"><input type="button" value="ok?" onclick="andiamo();"></div>
</body>
The window.opener.processRequest()
call is very important as it returns the control to the main page forcing main page javascript to complete the intended action.
回答8:
As of many answers you can't mask the input with a JavaScript prompt()
but some alternative way to done this functionality using custom solution or use password input box instead.
jQuery UI - Dialog Modal Form
Use a modal dialog to require that the user enter data during a multi-step process. Embed form markup in the content area, set the modal option to true, and specify primary and secondary user actions with the buttons option.
Ref : Dialog Modal Form
jQuery Impromptu plugin
Using html
option you write html tags.
Ref : Impromptu Plugin
Using JavaScript
Only by opening a little window containing a password form field:
<script language="JavaScript"><!--
function getPassword() {
WinId = window.open('','newwin','width=100,height=100');
if (!WinId.opener) WinId.opener = self;
Text = '<form ';
Text += 'onSubmit="opener.location=this.password.value + \'.html\'; self.close()">';
Text += '<input type="password" name="password">';
Text += '<\/form>';
WinId.document.open();
WinId.document.write(Text);
WinId.document.close();
}
//--></script>
Ref : irt.org
回答9:
alert("Username=Bob/Password=Pass <punctuation counts!>");
var user=prompt("Username")
var pass=prompt("Password")
if (user!=="Bob")
{
alert("Login was unsuccessful")
}
else
{
if (pass!=="Pass")
{
alert("Login was unsuccessful")
window.history.back()
}
}