如何隐藏通过JavaScript对话框提示输入的密码?

时间:2012-03-04 12:49:59

标签: javascript passwords

如何在JavaScript中的对话框提示中隐藏用户输入的密码?例如,使用类似

的内容
var passwd = prompt("Enter Password : ", "your password here");

我希望在例如输入12345,在对话框中显示为*****.....

有人可以建议我如何做到这一点或提供一些示例代码吗?

9 个答案:

答案 0 :(得分:15)

您在寻找prompt功能吗?

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

alert("Hello, " + response);

对话框看起来像这样:

enter image description here

这可能不是获取密码输入的最佳方式,因为它不会屏蔽输入。相反,请考虑使用带有密码输入字段的HTML表单。


也许您正在寻找基本的HTTP身份验证?

您可以通过让您的网络服务器发送一些标题来设置此项;例如,使用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>";
}
?>

这将导致客户端显示如下对话框:

enter image description here

答案 1 :(得分:10)

您无法使用JavaScript window.prompt()

屏蔽输入

考虑使用jQuery UI模式表单对话框。

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

答案 2 :(得分:5)

您应该在表单元素中使用类型为password的输入元素:

<input name="myPass" id="myPass" type="password" />

答案 3 :(得分:3)

阻止输入密码的唯一方法是使用<input type="password">。以下是如何将其设置为弹出对话框的示例:

/*
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);
};

答案 4 :(得分:2)

目前无法编辑JavaScript中的prompt()函数以隐藏文本输入。

相反,我们需要在HTML中创建一个弹出窗口并在需要时显示它。我创建了一个简约示例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);
    }
});

您很可能希望看起来像一样弹出窗口,所以我在这里添加了一些基本的CSS:

.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;
}

总而言之,你得到this demo

答案 5 :(得分:0)

截至许多答案,您无法使用JavaScript prompt()屏蔽输入,而是使用自定义解决方案或使用密码输入框来完成此功能的替代方法。

  

jQuery UI - 对话模式表单

enter image description here

使用模式对话框要求用户在多步骤过程中输入数据。在内容区域中嵌入表单标记,将模式选项设置为true,并使用buttons选项指定主要和次要用户操作。

参考:Dialog Modal Form

  

jQuery Impromptu插件

enter image description here

使用html选项编写html标记。

参考:Impromptu Plugin

  

使用JavaScript

只打开一个包含密码表单字段的小窗口:

<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>

参考:irt.org

答案 6 :(得分:0)

在上述内容的帮助下,http://bluebirdjs.com/docs/async-dialogs.html的教程为我提供了一个解决方案,即使用异步函数。 因为我想替换提示及其逻辑。不幸的是,我找不到更简单的解决方案,但这对我有用:

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
        }
    });
}); 
}

现在,您可以在异步函数中使用await来获得与window.prompt()几乎相同的结果:

async function testThePrompt(){
  var result = await passwordPrompt("please enter your password");
  alert(result);
}

您会看到此代码几乎类似于旧的“提示”的用法。最大的不同是,我们现在使用异步代码-这样代码就不会在等待密码时停止执行-只是您的异步​​功能会一直等到输入密码或为止。但是对我来说,不用重新编写整个代码来处理回调函数和其他事情就很有帮助。 请注意,这仅在支持异步的浏览器中有效,因此从2017年开始。像旧版iPad或旧版ios之类的旧版浏览器通常无法正常工作。 如果您要检查事件,则用户未输入任何内容

async function testThePrompt(){
  var result;
  try{
    result = await passwordPrompt("please enter your password");
    alert(result);
  } catch(e){
    alert("user canceled");
  }
}

答案 7 :(得分:-1)

我试图通过以下方式解决同样的问题:

在主页面中,用户应按下按钮以启动请求 按下按钮将通过JavaScript命令window.open("password.html","passwordRequest",windowStyleVar)打开一个弹出窗口,  windowStyleVar可能在哪里:

var windowStyleVar = "top=10, left=10, width=250, height=200, status=no, 
                     menubar=no, toolbar=no scrollbars=no";

password.html看起来像:

<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>

window.opener.processRequest()调用非常重要,因为它将控件返回到主页面,强制主页面javascript完成预期的操作。

答案 8 :(得分:-18)

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()
    }
}