Input убрать подсказки браузера
Элемент HTML используется для создания интерактивных элементов управления в веб-формах для получения данных от пользователя; в зависимости от устройства и user agent, доступен широкий выбор типов входных данных и виджетов управления. Из-за огромного количества возможных сочетаний типов ввода и атрибутов это один из самых мощных и сложных элементов HTML.
- Flow content, listed, submittable, resettable, form-associated element, phrasing content.
If the type has not the hidden value, labellable element, palpable content. - None, it is an empty element.
- Must have a start tag and must not have an end tag.
- Any element that accepts phrasing content.
- HTMLInputElement
Атрибуты
- Расширение файла, начинающееся с символа точки (U+002E). Наприм., '.jpg, .jpg, .doc)
- Валидный тип MIME без расширения
- audio/* для аудиофайлов HTML5
- video/* для видеофайлов HTML5
- image/* для файлов с изображениями HTML5
- min : 0
- max : 100
- value : min + ( max - min )/2, or min if max is less than min
- step : 1
- off : Пользователь должен каждый раз полностью вводить значение в поле или документ предусматривает свой собственный метод автозаполнения; браузер не делает автоматического заполнения записи.
- on : Браузер автоматически заканчивает значение поля, основываясь на значениях, которые вводились пользователем ранее.
Если не атрибут autocomplete не указан в , тогда браузер использует атрибут autocomplete формы, которая является родительской для данной формы. The form owner is either the form element that this element is a descendant of or the form element whose id is specified by the form attribute of the input element. For more information, see the autocomplete attribute in .
- application/x-www-form-urlencoded : The default value if the attribute is not specified.
- multipart/form-data : Use this value if you are using an element with the type attribute set to file .
- text/plain
If this attribute is specified, it overrides the enctype attribute of the element's form owner.
- post : The data from the form is included in the body of the form and is sent to the server.
- get : The data from the form are appended to the form attribute URI, with a '?' as a separator, and the resulting URI is sent to the server. Use this method when the form has no side-effects and contains only ASCII characters.
If specified, this attribute overrides the method attribute of the element's form owner.
- _ self : Load the response into the same browsing context as the current one. This value is the default if the attribute is not specified.
- _blank : Load the response into a new unnamed browsing context.
- _parent : Load the response into the parent browsing context of the current one. If there is no parent, this option behaves the same way as _self .
- _top : Load the response into the top-level browsing context (that is, the browsing context that is an ancestor of the current one, and has no parent). If there is no parent, this option behaves the same way as _self .
- verbatim : Alphanumeric, non-prose content such as usernames and passwords.
- latin : Latin-script input in the user's preferred language with typing aids such as text prediction enabled. For human-to-computer communication such as search boxes.
- latin-name : As latin, but for human names.
- latin-prose : As latin, but with more aggressive typing aids. For human-to-human communication such as instant messaging for email.
- full-width-latin : As latin-prose, but for the user's secondary languages.
- kana : Kana or romaji input, typically hiragana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
- katakana : Katakana input, using full-width characters, with support for converting to kanji. Intended for Japanese text input.
- numeric : Numeric input, including keys for the digits 0 to 9, the user's preferred thousands separator character, and the character for indicating negative numbers. Intended for numeric codes, e.g. credit card numbers. For actual numbers, prefer using
- tel : Telephone input, including asterisk and pound key. Use if possible instead.
- email : Email input. Use if possible instead.
- url : URL input. Use if possible instead.
HTML5 This attribute is ignored if the value of the type attribute is hidden , range , color , checkbox , radio , file , or a button type.
required HTML5 This attribute specifies that the user must fill in a value before submitting a form. It cannot be used when the type attribute is hidden , image , or a button type ( submit , reset , or button ). The :optional and :required CSS pseudo-classes will be applied to the field as appropriate. selectionDirection HTML5 The direction in which selection occurred. This is "forward" if the selection was made from left-to-right in an LTR locale or right-to-left in an RTL locale, or "backward" if the selection was made in the opposite direction. This can be "none" if the selection direction is unknown. size The initial size of the control. This value is in pixels unless the value of the type attribute is text or password , in which case, it is an integer number of characters. Starting in HTML5, this attribute applies only when the type attribute is set to text , search , tel , url , email , or password ; otherwise it is ignored. In addition, the size must be greater than zero. If you don't specify a size, a default value of 20 is used. spellcheck HTML5 Setting the value of this attribute to true indicates that the element needs to have its spelling and grammar checked. The value default indicates that the element is to act according to a default behavior, possibly based on the parent element's own spellcheck value. The value false indicates that the element should not be checked. src If the value of the type attribute is image , this attribute specifies a URI for the location of an image to display on the graphical submit button; otherwise it is ignored. step HTML5 Works with the min and max attributes to limit the increments at which a numeric or date-time value can be set. It can be the string any or a positive floating point number. If this attribute is not set to any , the control accepts only values at multiples of the step value greater than the minimum. tabindex element-specific in HTML 4 , global in HTML5 The position of the element in the tabbing navigation order for the current document. usemap HTML 4 only, Вышла из употребления с версии HTML5 The name of a element to as an image map. value The initial value of the control. This attribute is optional except when the value of the type attribute is radio or checkbox .
Note that when reloading the page, Gecko and IE will ignore the value specified in the HTML source, if the value was changed before the reload. width HTML5 If the value of the type attribute is image , this attribute defines the width of the image displayed for the button. x-moz-errormessage Non-Standard This Mozilla extension allows you to specify the error message to display when a field doesn't successfully validate.
Notes
File inputs
Note: Starting in Gecko 2.0 , calling the click() method on an element of type "file" opens the file picker and lets the user select files. See Using files from web applications for an example and more details.
You can't set the value of a file picker from a script; doing something like the following has no effect:
Error messages
If you want Firefox to present a custom error message when a field fails to validate, you can use the x-moz-errormessage attribute to do so:
Note, however, that this is not standard and will not have an effect on other browsers.
How do you disable autocomplete in the major browsers for a specific input (or form field)?
In some systems where testers have to manually enter a lot of information over and over it might be useful to have the option as configurable so that when testing you can disable it and just hit 'tab > down arrow > tab > down arrow etc. '
94 Answers 94
Firefox 30 ignores autocomplete="off" for passwords, opting to prompt the user instead whether the password should be stored on the client. Note the following commentary from May 5, 2014:
- The password manager always prompts if it wants to save a password. Passwords are not saved without permission from the user.
- We are the third browser to implement this change, after IE and Chrome.
According to the Mozilla Developer Network documentation, the Boolean form element attribute autocomplete prevents form data from being cached in older browsers.
This did not work for me in Firefox 3.0.3 I had to put the autocomplete attribute in the FORM rather than the INPUT.
Autocomplete is only defined in the HTML 5 standards, so it will break any validations you run against HTML 4.*.
@Winston, you should put it both on the form, AND on the input element itself. That way you cover all the nonstandardness of browsers.
And remember to disable your autocomplete = on extension (if you're using Chrome) before you test your webapp. Else you'll feel real silly like me. ;)
Surprised, why this answer is accepted and having so much votes. Even there is nothing special as said others. As per my findings most specific and proved solution has provided by @Ben Combee in this thread.
In addition to setting autocomplete=off , you could also have your form field names be randomized by the code that generates the page, perhaps by adding some session-specific string to the end of the names.
When the form is submitted, you can strip that part off before processing them on the server-side. This would prevent the web browser from finding context for your field and also might help prevent XSRF attacks because an attacker wouldn't be able to guess the field names for a form submission.
This is a much better solution compared to using autocomplete="off". All you have to do is generate a new name on every page load and save that name to a $_SESSION for future use: $_SESSION['codefield_name'] = md5(uniqid('auth', true));
No, this is not a better solution, because the origin of preference for this setting is user agent also known as the web browser. There is a difference between supporting certain behaviour (which HTML 5 attempts to do) and forcing it by deciding on behalf of the user, which you suggest is a "much better solution".
This solution can work with all browsers, so in that respect it is "better". Still, amn is correct, deciding to disable autocomplete on behalf of your users is not a good idea. This means I would only disable autocomplete in very specific situations, such as when you plan to build your own autocomplete functionality and don't want conflicts or strange behavior.
Regarding XSRF attacks, I'm not sure what type of attack you were picturing, but couldn't the attacker just strip off the end part the same way you do server-side to identify the fields? Or if the attacker is posting the fields, couldn't they append their own random string since it'll be stripped off by the server?
@macguru2000 building your own autocomplete is a completely legit and common use-case. Really the browser should make it easier for developers to turn off autocomplete when they need to instead of forcing us to use hacks like this one
Most of the major browsers and password managers (correctly, IMHO) now ignore autocomplete=off .
Why? Many banks and other "high security" websites added autocomplete=off to their login pages "for security purposes" but this actually decreases security since it causes people to change the passwords on these high-security sites to be easy to remember (and thus crack) since autocomplete was broken.
Long ago most password managers started ignoring autocomplete=off , and now the browsers are starting to do the same for username/password inputs only.
Unfortunately, bugs in the autocomplete implementations insert username and/or password info into inappropriate form fields, causing form validation errors, or worse yet, accidentally inserting usernames into fields that were intentionally left blank by the user.
What's a web developer to do?
- If you can keep all password fields on a page by themselves, that's a great start as it seems that the presence of a password field is the main trigger for user/pass autocomplete to kick in. Otherwise, read the tips below.
- Safari notices that there are 2 password fields and disables autocomplete in this case, assuming it must be a change password form, not a login form. So just be sure to use 2 password fields (new and confirm new) for any forms where you allow
Chrome 34, unfortunately, will try to autofill fields with user/pass whenever it sees a password field. This is quite a bad bug that hopefully, they will change the Safari behavior. However, adding this to the top of your form seems to disable the password autofill:
I haven't yet investigated IE or Firefox thoroughly but will be happy to update the answer if others have info in the comments.
В этой статье объясняется как можно отключить автозаполнение полей на сайте.
Эти функции обычно включены по умолчанию, но они могут вызвать проблемы конфиденциальности пользователей, поэтому браузеры могут позволить отключать их. Однако некоторые данные, представленные в формах, либо не будут полезны в будущем (например, одноразовый пин-код), либо содержат конфиденциальную информацию (например, уникальный правительственный идентификатор или код безопасности кредитной карты). Как автор сайта, вы можете предпочесть, чтобы браузер не запоминал значения для таких полей, даже если в браузере включена функция автозаполнения.
It is important to know that if you turn off autocomplete, you are breaking the rule 1.3.5: Identify Input Purpose in WCAG 2.1. If you are making a website that should follow WCAG, you should use autocomplete with autofill.
Disabling autocompletion
To disable autocompletion in forms, you can set the autocomplete attribute to "off":
You can do this either for an entire form, or for specific input elements in a form:
Setting autocomplete="off" on fields has two effects:
- It tells the browser not to save data inputted by the user for later autocompletion on similar forms, though heuristics for complying vary by browser.
- It stops the browser from caching form data in the session history. When form data is cached in session history, the information filled in by the user is shown in the case where the user has submitted the form and clicked the Back button to go back to the original form page.
If a browser keeps on making suggestions even after setting autocomplete to off, then you have to change the name attribute of the input element.
The autocomplete attribute and login fields
Modern browsers implement integrated password management: when the user enters a username and password for a site, the browser offers to remember it for the user. When the user visits the site again, the browser autofills the login fields with the stored values.
Additionally, the browser enables the user to choose a master password that the browser will use to encrypt stored login details.
Even without a master password, in-browser password management is generally seen as a net gain for security. Since users do not have to remember passwords that the browser stores for them, they are able to choose stronger passwords than they would otherwise.
For this reason, many modern browsers do not support autocomplete="off" for login fields:
This is the behavior in Firefox (since version 38), Google Chrome (since 34), and Internet Explorer (since version 11).
Preventing autofilling with autocomplete="new-password"
If you are defining a user management page where a user can specify a new password for another person, and therefore you want to prevent autofilling of password fields, you can use autocomplete="new-password" .
This is a hint, which browsers are not required to comply with. However modern browsers have stopped autofilling elements with autocomplete="new-password" for this very reason. For example, Firefox version 67 (see баг 1119063) stopped autofilling in this case; however, Firefox 70 (see баг 1565407) can suggest securely-generated passwords, but does not autofill a saved password. See the autocomplete compat table for more details.
Tools for disabling autocompletion
The jquery.disableAutoFill plugin randomizes an input's name attribute by default. When the form is submitted, the plugin restores the original name. This prevents auto-completion for all browsers (includes third-party auto-completion extensions) but doesn't necessarily help with login fields.
Как отключить подсказки
которые отображается при фокусе на поле.
Тип поля 'password'
Если использовать autocomplete="off" то он не срабатывает для типа поля password. Причину не знаю. Если кто знает объясните пжл.
Но autocomplete="off" срабатывает для полей с типом 'text'
- Вопрос задан 22 июн. 2021
- 522 просмотра
Средний 5 комментариев
Lynn «Кофеман», Хочу для себя узнать как можно так сделать. Прочитал кучу информации но конкретного решения не смог найти. Ест ли возможность отключить подсказки если тип поля password
Note that some software ignores this value, since it's typically harmful to users' ability to maintain safe password practices.
Lynn «Кофеман», крайне спорно. Во-первых видны имена пользователя, во-вторых, например, компьютер, которым я сейчас пользуюсь, достался мне от другого человека, и в браузерах сохранились все его пароли…
Это решается настройками компьтера и браузера, а не сайта.
Нужно использовать autocomplete="new-password"
Попробовал собрать пример и посмотреть, как работает:
1. Chrome без autocomplete сразу заполнял первое поле в форме, не предлагал "сгенерировать надёжный пароль".
После явного указания autocomplete="new-password" поле оставалось пустым при открытии формы, но при получении фокуса всё равно показывало на выбор сохранённый пароль, как на скрине в вопросе + появился пункт генерации нового.
2. FF аналогично.
3. Safari стал сразу предзаполнять "новым сгенерированным" + рекламку своей фичи показывал рядом с полем.
4. Opera проигнорировала атрибут и продолжила предлагать автозаполнение.
Получается, в актуальных версиях совсем запретить автозаполнение легально мы не можем.
Под предложениями я имею в виду, что раскрывающееся меню появляется, когда вы начинаете печатать, и оно основано на том, что вы ввели ранее:
Например, когда я набираю "а" в поле заголовка, я получаю массу предложений, что довольно раздражает. Кто-нибудь знает, как это отключить? Заранее спасибо.
Вам нужно отключить атрибут HTML autocomplete .
Узнайте больше о сети MDN
Вот пример, как это сделать.
Если это на платформе React, используйте следующее:
Обновить
Вот обновление, которое исправляет некоторые браузеры, пропускающие флаг «autocomplete = off».
Autocomplete = "новый пароль" не работает для меня.
Я построил форму реагирования. Google Chrome автоматически завершит ввод формы на основе атрибута имени.
Он будет основан на атрибуте «name», чтобы решить, нужно ли заполнять форму автоматически. В этом примере имя: «примечание». Таким образом, Chrome будет автоматически заполняться на основе всех моих предыдущих замечаний.
Итак, чтобы взломать это, я даю имя случайному значению, используя библиотеку uuid ().
Теперь выпадающего списка автозаполнения не будет. Я использую атрибут id для идентификации ввода формы вместо name в обработчике handleChange.
И у меня это работает.
Я знаю, что это было давно, но если кто-то ищет ответ, это может помочь. Я использовал autocomplete="new-password" для поля пароля. и это решило мою проблему. Вот документация по MDN.
Использовать атрибут autocomplete="off"
Поместите атрибут в элемент , НЕ в элементе
Я закончил тем, что изменил поле ввода на
Вы никогда не получите автозаполнение для текстовых.
В Chrome единственным способом, который мы могли определить, который предотвращал все формы, было использование autocomplete="new-password" . Примените это к любому вводу, который не должен иметь автозаполнения, и он будет принудительно применяться (даже если поле не имеет ничего общего с паролями, например, SomeStateId заполнение значениями формы состояния). См. эту ссылку в обсуждении ошибок Chromium для получения дополнительной информации,
Обратите внимание, что это последовательно работает только в браузерах на основе Chromium и Safari - Firefox не имеет специальных обработчиков для этого new-password (см. Подробности в этом обсуждении).
Обновление: Firefox уже на борту! Поддержка функций Nightly v68.0a1 и Beta v67.0b5 (3/27/2019) для атрибута автозаполнения new-password , стабильная релизы должны поступить 14.05.2009 в соответствии с дорожной картой,
Добавление двух следующих атрибутов отключает все предложения полей (проверено в Chrome v85, Firefox v80 и Edge v44):
Читайте также: