How can I get browser to prompt to save password?

前端 未结 20 1445
面向向阳花
面向向阳花 2020-11-22 16:20

Hey, I\'m working on a web app that has a login dialog that works like this:

  1. User clicks \"login\"
  2. Login form HTML is loaded with AJAX and displayed i
20条回答
  •  执笔经年
    2020-11-22 16:36

    None of the answers already make it clear you can use the HTML5 History API to prompt to save the password.

    First, you need to make sure you have at least a

    element with a password and email or username field. Most browsers handle this automatically as long as you use the right input types (password, email or username). But to be sure, set the autocomplete values correctly for each input element.

    You can find a list of the autocomplete values here: https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete

    The ones you need are: username, email and current-password

    Then you have two possibilities:

    • If you navigate away to a different URL after submitting, most browsers will prompt to save the password.
    • If you don't want to redirect to a different URL or even reload the page (e.g. a single page application). Just prevent the event defaults (using e.preventDefault) in your submit handler of the form. You can use the HTML5 history API to push something on the history to indicate you 'navigated' inside your single page application. The browser will now prompt to save the password and username.
    history.pushState({}, "Your new page title");
    

    You can also change the page's URL, but that is not required to prompt to save the password:

    history.pushState({}, "Your new page title", "new-url");
    

    Documentation: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState

    This has the additional benefit that you can prevent the browser to ask to save the password if the user entered the password incorrectly. Note that in some browsers the browser will always ask to save the credentials, even when you call .preventDefault and not use the history API.

    If you don't want to navigate away and/or modify the browser history, you can use replaceState instead (this also works).

提交回复
热议问题