处理Chrome预填充的问题

1,980 阅读1分钟

设计需求:

问题

在chrome浏览器中,登录的时候会提醒是否记录密码,点击确定之后,下次再进入此页面,浏览器会自动向输入框中天充值,背景未黄色, 但是在用户和浏览器产生交互(鼠标点击等)之前,用js或取值并获取不到(预填充),这样也就出现了用户可以看到输入框中有值,但是由于js未获取到值,提交按钮还显示的灰色禁用状态

360浏览器填充是真正的填充

解决方案

<input name="username" ref="username" />
<input password="password" ref="password" />
<button type="button" :disabled="buttonDisabled">提交</button>
export default {
    data() {
        return {
            username: '',
            password: '',
            // 用户名是否被浏览器自动填充
            usernameBrowserFilled: false,
            // 密码是否被浏览器自动填充
            passwordBrowserFilled: false,
        }
    },
    computed: {
        buttonDisabled() {
            // 填充就代表输入框中有值,都然获取不到
            return (this.username || this.usernameBrowserFilled) && (this.password && this.passwordBrowserFilled)
        }
    },
    mouneted() {
        this.addInputBrowserFillListener()
    },
    methods: {
        addInputBrowserFillListener() {
             detectingBrowserAutofill({
              input: this.$refs.username,
              onAutoFillStart: (input) => {
                this.usernameBrowserFilled = true
              },
              onAutoFillCancel: (input) => {
                this.usernameBrowserFilled = false
              }
            })
            detectingBrowserAutofill({
              input: this.$refs.password,
              onAutoFillStart: (input) => {
                this.passwordBrowserFilled = true
              },
              onAutoFillCancel: (input) => {
                this.passwordBrowserFilled = false
              }
            })
        },
        detectingBrowserAutofill({input, onAutoFillStart, onAutoFillCancel}) {
            const onAnimationStart = ({target, animationName}) => {
                switch (animationName) {
                  case 'onAutoFillStart':
                    return onAutoFillStart(target)
                  case 'onAutoFillCancel':
                      return onAutoFillCancel(target)
                }
            }
            // input添加监听, 动画的产生看下面的css
            input.addEventListener('animationstart', onAnimationStart, false)
        }
    }
}
@keyframes onAutoFillStart {
  from {/**/}
  to {/**/}
}

@keyframes onAutoFillCancel {
  from {/**/}
  to {/**/}
}

input:-webkit-autofill {
  // Expose a hook for JavaScript when auto fill is shown.
  // JavaScript can capture 'animationstart' events
  animation-name: onAutoFillStart;

  // Make the backgound color become yellow _really slowly_
  transition: background-color 1s ease-in-out 0s;
}

input:not(:-webkit-autofill) {
  // Expose a hook for JS onAutoFillCancel
  // JavaScript can capture 'animationstart' events
  animation-name: onAutoFillCancel;
  //transition: background-color 0.2s ease-in-out 0s;
}

参考资料

相关问题提问

解决方案出处

bumfo.github.io/l.html

segmentfault.com/q/101000000…