Chrome Autofill/Autocomplete no value for password

后端 未结 20 1989
逝去的感伤
逝去的感伤 2020-11-27 02:57

When you have saved username and password for some site Chrome will autofill that username and password, but if you try to get the value for the password input field it is e

20条回答
  •  伪装坚强ぢ
    2020-11-27 03:08

    Continuing from what Andy Mercer said, here's my work around. Like a lot of people, I don't need the actual password value. I really just need to know that the password box has been autofilled, so that I can display the proper validation messages.

    Personally, I would not use suggested solution to detect the background color change cause by Chrome's autofill. That approach seems brittle. It depends on that yellow color never changing. But that could be changed by an extension and be different in another Blink based browser (ie. Opera). Plus, there's no promise Google wont use a different color in the future. My method works regardless of style.

    First, in CSS I set the content of the INPUT when the -webkit-autofil pseudo-class is applied to it:

    input:-webkit-autofill {
      content: "\feff"
    }
    

    Then, I created a routine to check for the content to be set:

    const autofillContent = `"${String.fromCharCode(0xFEFF)}"`;
    function checkAutofill(input) {
        if (!input.value) {
            const style = window.getComputedStyle(input);
            if (style.content !== autofillContent)
                return false;
        }
    
        //the autofill was detected
        input.classList.add('valid'); //replace this. do want you want to the input
        return true;
    }
    

    Lastly, I polled the input to allow the autofill time to complete:

    const input = document.querySelector("input[type=password]");
    
    if (!checkAutofill(input)) {
        let interval = 0;
        const intervalId = setInterval(() => {
            if (checkAutofill(input) || interval++ >= 20)
                clearInterval(intervalId);
        }, 100);
    }
    

提交回复
热议问题