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

前端 未结 9 2022
死守一世寂寞
死守一世寂寞 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: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

提交回复
热议问题