How can I get browser to prompt to save password?
Asked Answered
S

21

177

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 in DIV on page
  3. User enters user/pass in fields and clicks submit. It's NOT a <form> -- user/pass are submitted via AJAX
  4. If user/pass are okay, page reloads with user logged in.
  5. If user/pass are bad, page does NOT reload but error message appears in DIV and user gets to try again.

Here's the problem: the browser never offers the usual "Save this password? Yes / Never / Not Now" prompt that it does for other sites.

I tried wrapping the <div> in <form> tags with "autocomplete='on'" but that made no difference.

Is it possible to get the browser to offer to store the password without a major rework of my login flow?

thanks Eric

p.s. to add to my question, I'm definitely working with browers that store passwords, and I've never clicked "never for this site" ...this is a technical issue with the browser not detecting that it's a login form, not operator error :-)

Sporocyte answered 4/3, 2010 at 20:1 Comment(3)
Don't forget that not all browsers can store passwords.Azrael
mabe the browser offered to save your user/pass and you clicked "Never ask again!" ?Naturalistic
Related: #6143225Bursiform
Z
75

I found a complete solution for this question. (I've tested this in Chrome 27 and Firefox 21).

There are two things to know:

  1. Trigger 'Save password', and
  2. Restore the saved username/password

1. Trigger 'Save password':

For Firefox 21, 'Save password' is triggered when it detects that there is a form containing input text field and input password field is submitted. So we just need to use

$('#loginButton').click(someFunctionForLogin);
$('#loginForm').submit(function(event){event.preventDefault();});

someFunctionForLogin() does the ajax login and reload/redirect to the signed in page while event.preventDefault() blocks the original redirection due to submitting the form.

If you deal with Firefox only, the above solution is enough but it doesn't work in Chrome 27. Then you will ask how to trigger 'Save password' in Chrome 27.

For Chrome 27, 'Save password' is triggered after it is redirected to the page by submitting the form which contains input text field with attribute name='username' and input password field with attribute name='password'. Therefore, we cannot block the redirection due to submitting the form but we can make the redirection after we've done the ajax login. (If you want the ajax login not to reload the page or not to redirect to a page, unfortunately, my solution doesn't work.) Then, we can use

<form id='loginForm' action='signedIn.xxx' method='post'>
    <input type='text' name='username'>
    <input type='password' name='password'>
    <button id='loginButton' type='button'>Login</button>
</form>
<script>
    $('#loginButton').click(someFunctionForLogin);
    function someFunctionForLogin(){
        if(/*ajax login success*/) {
            $('#loginForm').submit();
        }
        else {
            //do something to show login fail(e.g. display fail messages)
        }
    }
</script>

Button with type='button' will make the form not to be submitted when the button is clicked. Then, binding a function to the button for ajax login. Finally, calling $('#loginForm').submit(); redirects to the signed-in page. If the signed-in page is current page, then you can replace 'signedIn.xxx' by current page to make the 'refresh'.

Now, you will find that the method for Chrome 27 also works in Firefox 21. So it is better to use it.

2. Restore the saved username/password:

If you already have the loginForm hard-coded as HTML, then you will found no problem to restore the saved password in the loginForm.
However, the saved username/password will not be bind to the loginForm if you use js/jquery to make the loginForm dynamically, because the saved username/password is bind only when the document loads.
Therefore, you needed to hard-code the loginForm as HTML and use js/jquery to move/show/hide the loginForm dynamically.


Remark: If you do the ajax login, do not add autocomplete='off' in tag form like

<form id='loginForm' action='signedIn.xxx' autocomplete='off'>

autocomplete='off' will make the restoring username/password into the loginForm fails because you do not allow it 'autocompletes' the username/password.

Zingale answered 16/6, 2013 at 12:11 Comment(7)
In Chrome the 'event.preventDefault()' prevents the "Save password" prompt to be shown, see this bug: code.google.com/p/chromium/issues/detail?id=282488Macro
For anyone else who stumbles across this, I think they are releasing a fix for it: code.google.com/p/chromium/issues/detail?id=357696Vermifuge
Lots of users are using ENTER key to submit the form, since you have prevented default when user submitted the form, nothing will happen, that is bad UX. You can check for the enter key keycode when submitting, however you will get again to the begging...Montgomery
Chrome 46 fixed its wrong behaviour - no workarounds needed anymore. See https://mcmap.net/q/144297/-getting-chrome-to-prompt-to-save-password-when-using-ajax-to-loginMacro
Are there some docs where I can see what name-attribute values are "allowed" by Google Chrome? Currently my field was named identity and chrome didn't prompt the save password dialogScreen
Does not work reliably, some browsers do not trigger the "remember" feature if you submit from Javascript.Diploblastic
Safari is the problem browser for me here.Heiskell
B
50

Using a button to login:

If you use a type="button" with an onclick handler to login using ajax, then the browser won't offer to save the password.

<form id="loginform">
 <input name="username" type="text" />
 <input name="password" type="password" />
 <input name="doLogin"  type="button" value="Login" onclick="login(this.form);" />
</form>

Since this form does not have a submit button and has no action field, the browser will not offer to save the password.


Using a submit button to login:

However, if you change the button to type="submit" and handle the submit, then the browser will offer to save the password.

<form id="loginform" action="login.php" onSubmit="return login(this);">
 <input name="username" type="text" />
 <input name="password" type="password" />
 <input name="doLogin"  type="submit" value="Login" />
</form>

Using this method, the browser should offer to save the password.


Here's the Javascript used in both methods:

function login(f){
    var username = f.username.value;
    var password = f.password.value;

    /* Make your validation and ajax magic here. */

    return false; //or the form will post your data to login.php
}
Banzai answered 13/11, 2011 at 1:40 Comment(5)
@Bigood Because it works while the accepted answer didn't (for me, at least). Thanks spetson!Quartziferous
Works for me in IE as well. I could kiss you now!Hottentot
Worked for me too.. :)Lollis
This is the correct one and also the most elegant solution to the problem.Crumpet
It works because of I simply copy 2nd code and paste it into login page via inspect element, Enter username/password in newly added filed on that page and press login then it prompt me to save user/password. Then I refresh page and voila, It prompt me to choose already saved user/pass ;)Diphenylamine
F
15

I have been struggling with this myself, and I finally was able to track down the issue and what was causing it to fail.

It all stemmed from the fact that my login form was being dynamically injected into the page (using backbone.js). As soon as I embed my login form directly into my index.html file, everything worked like a charm.

I think this is because the browser has to be aware that there is an existing login form, but since mine was being dynamically injected into the page, it didn't know that a "real" login form ever existed.

Fee answered 7/6, 2012 at 23:5 Comment(1)
Starting with Chrome version 46 you can now also dynamically inject forms and they will be recognized as "real" login form which credentials can be saved. See https://mcmap.net/q/144297/-getting-chrome-to-prompt-to-save-password-when-using-ajax-to-loginMacro
A
13

Simple 2020 aproach

This will automatically enable autocomplete and save password in browsers.

  • autocomplete="on" (form)
  • autocomplete="username" (input, email/username)
  • autocomplete="current-password" (input, password)
<form autocomplete="on">
  <input id="user-text-field" type="email" autocomplete="username"/>
  <input id="password-text-field" type="password" autocomplete="current-password"/>
</form>

Check out more at Apple's documentation: Enabling Password AutoFill on an HTML Input Element

Argeliaargent answered 9/3, 2020 at 20:5 Comment(1)
FYI this seems to require form submission (can't use XHR and preventDefault) and it won't work if there is only a single password field (digital-safe type applications). Sharing these findings for anyone else who might find it useful.Anonymous
G
12

This solution worked for me posted by Eric on the codingforums


The reason why it does not prompt it is because the browser needs the page to phyiscally to refresh back to the server. A little trick you can do is to perform two actions with the form. First action is onsubmit have it call your Ajax code. Also have the form target a hidden iframe.

Code:

<iframe src="ablankpage.htm" id="temp" name="temp" style="display:none"></iframe>
<form target="temp" onsubmit="yourAjaxCall();">

See if that causes the prompt to appear.

Eric


Posted on http://www.codingforums.com/showthread.php?t=123007

Gittle answered 25/1, 2011 at 15:32 Comment(3)
As a note, I found that Chrome 11 does not offer to save your credentials if the form is submitted to itself. So you need to set action to some dummy page.Bursiform
This will send the password plaintext in the url as a get request. If method is changed to POST, Firefox (16) will open the formerly hidden frame in a new tab. The same is true for chrome on android 4. :-(Forage
Chrome 46 fixed its wrong behaviour - no iframe workarounds needed anymore. See https://mcmap.net/q/144297/-getting-chrome-to-prompt-to-save-password-when-using-ajax-to-loginMacro
O
11

There's an ultimate solution to force all browsers (tested: chrome 25, safari 5.1, IE10, Firefox 16) to ask for save the password using jQuery and ajax request:

JS:

$(document).ready(function() {
    $('form').bind('submit', $('form'), function(event) {
        var form = this;

        event.preventDefault();
        event.stopPropagation();

        if (form.submitted) {
            return;
        }

        form.submitted = true;

        $.ajax({
            url: '/login/api/jsonrpc/',
            data: {
                username: $('input[name=username]').val(),
                password: $('input[name=password]').val()
            },
            success: function(response) {
                form.submitted = false;
                form.submit(); //invoke the save password in browser
            }
        });
    });
});

HTML:

<form id="loginform" action="login.php" autocomplete="on">
    <label for="username">Username</label>
    <input name="username" type="text" value="" autocomplete="on" />
    <label for="password">Password</label>
    <input name="password" type="password" value="" autocomplete="on" />
   <input type="submit" name="doLogin" value="Login" />
</form>

The trick is in stopping the form to submit its own way (event.stopPropagation()), instead send your own code ($.ajax()) and in the ajax's success callback submit the form again so the browser catches it and display the request for password save. You may also add some error handler, etc.

Hope it helped to someone.

Osculum answered 28/3, 2013 at 11:36 Comment(3)
This will actually do a HTTP get to the login.php?username=username&password=password which defats the whole purpose of saving password in the first placeAvelin
Wooooooooooooooooooooooooooooooooooooooooooooooh ! That worked for me ;) thanks a lot !Folkway
Yep, add event listener to form and add event.preventDefault() plus event.stopPropagation()Symmetrical
T
7

I tried spetson's answer but that didn't work for me on Chrome 18. What did work was to add a load handler to the iframe and not interrupting the submit (jQuery 1.7):

function getSessions() {
    $.getJSON("sessions", function (data, textStatus) {
        // Do stuff
    }).error(function () { $('#loginForm').fadeIn(); });
}
$('form', '#loginForm').submit(function (e) {
    $('#loginForm').fadeOut();
}); 
$('#loginframe').on('load', getSessions);
getSessions();

The HTML:

<div id="loginForm">
    <h3>Please log in</h3>
    <form action="/login" method="post" target="loginframe">
            <label>Username :</label>
            <input type="text" name="login" id="username" />
            <label>Password :</label>
            <input type="password" name="password" id="password"/>
            <br/>
            <button type="submit" id="loginB" name="loginB">Login!</button>
    </form>
</div>
<iframe id="loginframe" name="loginframe"></iframe>

getSessions() does an AJAX call and shows the loginForm div if it fails. (The web service will return 403 if the user isn't authenticated).

Tested to work in FF and IE8 as well.

Tristich answered 2/2, 2012 at 17:15 Comment(2)
I tried this method in Chrome, and it wouldn't work unless the action page (/login in your example) returned some text or other visible content.Execrable
Chrome 46 fixed its wrong behaviour - no iframe workarounds needed anymore. See https://mcmap.net/q/144297/-getting-chrome-to-prompt-to-save-password-when-using-ajax-to-loginMacro
F
7

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 <form> 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).

Fructuous answered 12/5, 2020 at 13:40 Comment(1)
this is the year 2020 answer! I had to use history.pushState({}, null "Your new page title"); to get the url changed without any navigationGuardroom
R
6

The browser might not be able to detect that your form is a login form. According to some of the discussion in this previous question, a browser looks for form fields that look like <input type="password">. Is your password form field implemented similar to that?

Edit: To answer your questions below, I think Firefox detects passwords by form.elements[n].type == "password" (iterating through all form elements) and then detects the username field by searching backwards through form elements for the text field immediately before the password field (more info here). From what I can tell, your login form needs to be part of a <form> or Firefox won't detect it.

Revelationist answered 4/3, 2010 at 20:7 Comment(3)
It's similar, yes, thanks I'll accept this as the official answer since this is about as close as we're getting. Here's something frustrating: I can't seem to find (anywhere on the web) a simple blog post that says "Here are the rules that browsers use to detect if the form you're filling out is a login form, so they can offer to save the user's password." Considering this is a bit of black magic (and considering Mozilla, at least, is open source), you'd think someone would just publish the heuristics.Sporocyte
(And similarly, there doesn't seem to be a way for me to "hint" my login form so the browser knows it's a login form. Again, surprised this isn't better documented out there on the web. I think my changes will be to the form field names and the overall HTML structure, and then I hope [!] that fixes the problem.)Sporocyte
Okay, no luck. I've asked a new question, approaching this from a slightly different angle: #2399263Sporocyte
B
2

I spent a lot of time reading the various answers on this thread, and for me, it was actually something slightly different (related, but different). On Mobile Safari (iOS devices), if the login form is HIDDEN when the page loads, the prompt will not appear (after you show the form then submit it). You can test with the following code, which displays the form 5 seconds after the page load. Remove the JS and the display: none and it works. I am yet to find a solution to this, just posted in case anyone else has the same issue and can not figure out the cause.

JS:

$(function() {
  setTimeout(function() {
    $('form').fadeIn();
  }, 5000);
});

HTML:

<form method="POST" style="display: none;">
  <input name='email' id='email' type='email' placeholder='email' />
  <input name='password' id='password' type='password' placeholder='password' />
  <button type="submit">LOGIN</button>
</form>
Bremsstrahlung answered 13/11, 2012 at 1:53 Comment(0)
A
1

The following code is tested on

  • Chrome 39.0.2171.99m: WORKING
  • Android Chrome 39.0.2171.93: WORKING
  • Android stock-browser (Android 4.4): NOT WORKING
  • Internet Explorer 5+ (emulated): WORKING
  • Internet Explorer 11.0.9600.17498 / Update-Version: 11.0.15: WORKING
  • Firefox 35.0: WORKING

JS-Fiddle:
http://jsfiddle.net/ocozggqu/

Post-code:

// modified post-code from https://mcmap.net/q/45092/-javascript-post-request-like-a-form-submit
function post(path, params, method)
{
    method = method || "post"; // Set method to post by default if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.

    var form = document.createElement("form");
    form.id = "dynamicform" + Math.random();
    form.setAttribute("method", method);
    form.setAttribute("action", path);
    form.setAttribute("style", "display: none");
    // Internet Explorer needs this
    form.setAttribute("onsubmit", "window.external.AutoCompleteSaveForm(document.getElementById('" + form.id + "'))");

    for (var key in params)
    {
        if (params.hasOwnProperty(key))
        {
            var hiddenField = document.createElement("input");
            // Internet Explorer needs a "password"-field to show the store-password-dialog
            hiddenField.setAttribute("type", key == "password" ? "password" : "text");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
        }
    }

    var submitButton = document.createElement("input");
    submitButton.setAttribute("type", "submit");

    form.appendChild(submitButton);

    document.body.appendChild(form);

    //form.submit(); does not work on Internet Explorer
    submitButton.click(); // "click" on submit-button needed for Internet Explorer
}

Remarks

  • For dynamic login-forms a call to window.external.AutoCompleteSaveForm is needed
  • Internet Explorer need a "password"-field to show the store-password-dialog
  • Internet Explorer seems to require a click on submit-button (even if it's a fake click)

Here is a sample ajax login-code:

function login(username, password, remember, redirectUrl)
{
    // "account/login" sets a cookie if successful
    return $.postJSON("account/login", {
        username: username,
        password: password,
        remember: remember,
        returnUrl: redirectUrl
    })
    .done(function ()
    {
        // login succeeded, issue a manual page-redirect to show the store-password-dialog
        post(
            redirectUrl,
            {
                username: username,
                password: password,
                remember: remember,
                returnUrl: redirectUrl
            },
            "post");
    })
    .fail(function ()
    {
        // show error
    });
};

Remarks

  • "account/login" sets a cookie if successful
  • Page-redirect ("manually" initiated by js-code) seems to be required. I also tested an iframe-post, but I was not successful with that.
Anglican answered 16/1, 2015 at 8:58 Comment(0)
G
1

I found a fairly elegant solution (or hack, whatever fits) for Prototype.JS users, being one of the last holdouts using Prototype. A simple substitution of corresponding jQuery methods should do the trick.

First, make sure there's a <form> tag, and a submit button with a class name that can be referenced later (in this case faux-submit) that is nested inside an element with a style set to display:none, as illustrated below:

<form id="login_form" action="somewhere.php" method="post">
    <input type="text" name="login" />
    <input type="password" name="password" />
    <div style="display:none">
        <input class="faux-submit" type="submit" value="Submit" />
    </div>
    <button id="submit_button">Login</button>
</form>

Then create a click observer for the button, that will "submit" the form as illustrated:

$('submit_button').observe('click', function(event) {
    $('login_form').submit();
});

Then create a listener for submit event, and stop it. event.stop() will stop all submit events in the DOM unless it's wrapped in Event.findElement with the class of the hidden input button (as above, faux-submit):

document.observe('submit', function(event) {
    if (event.findElement(".faux-submit")) { 
        event.stop();
    }
});

This is tested as working in Firefox 43 and Chrome 50.

Geodynamics answered 28/5, 2016 at 17:1 Comment(0)
P
0

Your site is probably already in the list where the browser is told not to prompt for saving a password. In firefox, Options -> Security -> Remember password for sites[check box] - exceptions[button]

Patter answered 4/3, 2010 at 20:6 Comment(0)
D
0

add a bit more information to @Michal Roharik 's answer.

if your ajax call will return a return url, you should use jquery to change the form action attribute to that url before calling form.submit

ex.

$(form).attr('action', ReturnPath);
form.submitted = false;
form.submit(); 
Diabolic answered 6/5, 2013 at 20:34 Comment(0)
I
0

I had similar problem, login was done with ajax, but browsers (firefox, chrome, safari and IE 7-10) would not offer to save password if form (#loginForm) is submitted with ajax.

As a SOLUTION I have added hidden submit input (#loginFormHiddenSubmit) to form that was submitted by ajax and after ajax call would return success I would trigger a click to hidden submit input. The page any way needed to refreshed. The click can be triggered with:

jQuery('#loginFormHiddenSubmit').click();

Reason why I have added hidden submit button is because:

jQuery('#loginForm').submit();

would not offer to save password in IE (although it has worked in other browsers).

Impervious answered 25/9, 2013 at 18:21 Comment(0)
C
0

I have tried all the ways. Nothing works completely. This is my solution. It works for me. I hope it will work for you. I replace the email/username input with a textarea

<form>
<textarea required placeholder="Email" rows=1></textarea>
<input required placeholder="Password" type="password" readonly onfocus="this.removeAttribute('readonly')" />
<button>
    Sign in
</button>
Casals answered 19/5, 2022 at 11:41 Comment(0)
E
0
<form id='login' action='javascript:login()'>
    <input type='text' name='username'> // required for Safari
    <input type='password'> // required for Chrome
    <button type='submit' form='login'>Log In</button>
</form>

Worked for Chrome, Firefox, and Safari.

Erinerina answered 11/4, 2023 at 20:46 Comment(0)
A
-1

Not every browser (e.g. IE 6) has options to remember credentials.

One thing you can do is to (once the user successfully logs in) store the user information via cookie and have a "Remember Me on this machine" option. That way, when the user comes again (even if he's logged off), your web application can retrieve the cookie and get the user information (user ID + Session ID) and allow him/her to carry on working.

Hope this can be suggestive. :-)

Azrael answered 4/3, 2010 at 20:10 Comment(4)
I wouldn't store user information in a cookie, at least anything sensitive.Manufacturer
I didn't mean store the user password. Obviously you would have to be very creative in how you will have to create useful garbage to identify user info. Even SO stores info in cookie in order to recognise you.Azrael
fair enough, but i'd still encrypt as much as you could.Manufacturer
@JackMarchetti encrypting it client side would be a bad (and kinda useless) idea. Since the code needed to encrypt is visible, anyone can find the .js file and decrypt it. This means that you should not store the data in a cookieFairyfairyland
H
-1

You may attach the dialog to the form, so all those inputs are in a form. The other thing is make the password text field right after the username text field.

Halfwit answered 1/12, 2011 at 16:35 Comment(0)
W
-1

This work much better for me, because it's 100% ajaxed and the browser detects the login.

<form id="loginform" action="javascript:login(this);" >
 <label for="username">Username</label>
 <input name="username" type="text" value="" required="required" />
 <label for="password">Password</label>
 <input name="password" type="password" value="" required="required" />
 <a href="#" onclick="document.getElementById("loginform").submit();"  >Login</a>
</form>
Wards answered 21/1, 2014 at 15:5 Comment(0)
R
-3

Using a cookie would probably be the best way to do this.

You could have a checkbox for 'Remember me?' and have the form create a cookie to store the //user's login// info. EDIT: User Session Information

To create a cookie, you'll need to process the login form with PHP.

Rocca answered 4/3, 2010 at 20:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.