Disabling Safari autofill on usernames and passwords

后端 未结 17 1719
萌比男神i
萌比男神i 2020-11-29 03:52

You might already know, that Safari has a nasty autofill bug where it fills email, username and password fields no matter if you set autocomplete=\"off\" or not

17条回答
  •  时光取名叫无心
    2020-11-29 04:32

    The CSS display: none solutions mentioned here did not work for me (October 2016). I fixed this issue with JavaScript.

    I don't mind the browser remembering passwords, but wanted to prevent a bad autofill. In my case, a form with a password field and no associated username field. (User edit form in Drupal 7 site, where the password field is required only for some operations.) Whatever I tried, Safari would find a victim field for the username of the autofilled password (the field placed visually before, for instance).

    I'm restoring the original value as soon as Safari does the autofill. I'm trying this only for the first 2 seconds after page load. Probably even lower value is OK. My tests showed the autofill happens around 250 ms after page load (though I imagine this number depends a lot on how the page is constructed and loaded).

    Here's my JavaScript code (with jQuery):

    // Workaround for Safari autofill of the e-mail field with the username.
    // Try every 50ms during 2s to reset the e-mail to its original value.
    // Prevent this reset if user might have changed the e-mail himself, by
    // detecting focus on the field.
    if ($('#edit-mail').length) {
      var element = $('#edit-mail');
      var original = element.attr('value');
      var interval = setInterval(function() {
        if ($(document.activeElement).is(element)) {
          stop();
        } else if (element.val() != original) {
          element.val(original);
          stop();
        }
      }, 50);
      var stop = function() {
        clearTimeout(timeout);
        clearInterval(interval);
      }
      var timeout = setTimeout(function() {
        clearInterval(interval);
      }, 2000);
    }
    

提交回复
热议问题