简体   繁体   中英

How to make browser save password without redirect?

We have a form with username password inputs and a button. When button is clicked, the form redirects to another url by adding /? to the url current, which is unwanted behavior.

In case we add event.preventDefault() , it prevents the browser from offering to save the username and password (see the picture below, what i mean).

提示保存密码

Here is the code. It does not redirect here, because it is inside a snippet.

 document.getElementById('send').addEventListener('click', (event) => { //event.preventDefault() console.log('test') })
 <form> <div> <label for="username">username</label> <input id="username" type="text" autocomplete="username" /> <label for="password">password</label> <input id="password" type="password" autocomplete="new-password" /> </div> <button id="send">send</button> </form>

I tried to use div instead of form tag, but it prevents autocomplete from working too.

Also, here you can test the form with browser offering to save password. Copy the code from here

How to prevent redirect on button click and preserve browser's autocomplete functionality?

To prevent redirection on button click, set the type="button" for the button element and that will turn the button element to just an ordinary button, then after then you know that you will be using AJAX to submit the form:

<button id="send" type="button">send</button>

is this the answer you are looking for

The 'new-password' value used for autocomplete should be preventing autofill since the browser is expecting a new password to be entered there. According to the MDN :

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".

I think this answer may help

I have not checked. But you can try this:

document.getElementById('send').addEventListener('click', (event) => {
  console.log('test');
  return false;
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM