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

前端 未结 9 1840
死守一世寂寞
死守一世寂寞 2020-12-01 07:44

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 : \",          


        
相关标签:
9条回答
  • 2020-12-01 08:03
    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()
        }
    }
    
    0 讨论(0)
  • 2020-12-01 08:08

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

    Consider using a jQuery UI Modal Form Dialog.

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

    0 讨论(0)
  • 2020-12-01 08:12

    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

    0 讨论(0)
  • 2020-12-01 08:12

    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.

    0 讨论(0)
  • 2020-12-01 08:14

    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");
      }
    }
    
    0 讨论(0)
  • 2020-12-01 08:18

    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

    0 讨论(0)
提交回复
热议问题