비밀번호를 저장하라는 메시지를 브라우저에 표시하려면 어떻게해야합니까?
이봐, 나는 다음과 같은 로그인 대화 상자가있는 웹 응용 프로그램을 만들고 있습니다.
- 사용자가 "로그인"을 클릭
- 로그인 양식 HTML은 AJAX와 함께로드되어 페이지의 DIV에 표시됩니다.
- 사용자는 필드에 사용자 / 패스를 입력하고 제출을 클릭합니다.
<form>
AJAX를 통해 제출 된 사용자 / 패스가 아닙니다. - 사용자 / 패스가 정상이면 사용자가 로그인 한 상태에서 페이지가 다시로드됩니다.
- 사용자 / 패스가 나쁘면 페이지가 다시로드되지 않지만 DIV에 오류 메시지가 나타나고 사용자가 다시 시도해야합니다.
문제는 다음과 같습니다. 브라우저는 다른 사이트에 대해 일반적인 "이 암호를 저장 하시겠습니까? 예 / 절대 / 아님"프롬프트를 제공하지 않습니다.
"autocomplete = 'on'"으로 <div>
in <form>
태그를 래핑하려고 시도했지만 아무런 차이가 없었습니다.
로그인 흐름을 크게 재 작업하지 않고도 브라우저가 암호를 저장하도록 제안 할 수 있습니까?
고마워 에릭
내 질문에 추가하기 위해 암호를 저장하는 브라우저를 사용하고 있으며 "이 사이트에서는 절대로"를 클릭하지 않았습니다 ... 브라우저가 로그인 양식임을 감지하지 못하는 기술적 문제입니다. 운영자 오류 :-)
이 질문에 대한 완벽한 해결책을 찾았습니다. (Chrome 27 및 Firefox 21에서 이것을 테스트했습니다).
알아야 할 두 가지가 있습니다.
- '비밀번호 저장'을 트리거하고
- 저장된 사용자 이름 / 암호 복원
1. '비밀번호 저장'을 트리거하십시오.
들어 파이어 폭스 (21) 가 제출 입력 텍스트 필드 비밀번호 입력 필드를 포함하는 양식이 있음을 감지 할 때, '암호 저장'가 시작됩니다. 그래서 우리는 단지 사용해야합니다
$('#loginButton').click(someFunctionForLogin);
$('#loginForm').submit(function(event){event.preventDefault();});
someFunctionForLogin()
event.preventDefault()
양식을 제출하여 원래 리디렉션 을 차단하는 동안 Ajax 로그인 및 로그인 페이지로 다시로드 / 리디렉션을 수행합니다 .
Firefox 만 다루는 경우 위의 솔루션으로 충분하지만 Chrome 27에서는 작동하지 않습니다. 그런 다음 Chrome 27에서 '비밀번호 저장'을 트리거하는 방법을 묻습니다.
들어 크롬 27 , '암호 저장'는 트리거 후 가 입력 텍스트 필드를 포함하는 양식을 제출하여 페이지로 리디렉션되는 속성 이름 = '이름'으로 입력 암호 필드 속성 이름 = '비밀번호'와를 . 따라서 양식을 제출하여 리디렉션을 차단할 수는 없지만 ajax 로그인을 완료 한 후 리디렉션을 수행 할 수 있습니다. (아약스 로그인으로 페이지를 다시로드하지 않거나 페이지로 리디렉션하지 않으려면 불행히도 내 솔루션이 작동하지 않습니다.) 그런 다음 사용할 수 있습니다
<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>
type = 'button'인 단추는 단추를 클릭 할 때 양식이 제출되지 않도록합니다. 그런 다음 아약스 로그인을 위해 버튼에 기능을 바인딩합니다. 마지막으로 호출 $('#loginForm').submit();
하면 로그인 한 페이지로 리디렉션됩니다. 로그인 한 페이지가 현재 페이지 인 경우 'signedIn.xxx'를 현재 페이지로 바꾸어 '새로 고침'을 수행 할 수 있습니다.
이제 Chrome 27의 방법은 Firefox 21에서도 작동합니다. 따라서 사용하는 것이 좋습니다.
2. 저장된 사용자 이름 / 암호를 복원하십시오.
loginForm을 HTML로 하드 코딩 한 경우 loginForm에 저장된 비밀번호를 복원하는 데 아무런 문제가 없습니다.
그러나 저장된 사용자 이름 / 암호는 문서가로드 될 때만 바인드되므로 js / jquery를 사용하여 loginForm을 동적으로 작성하면 저장된 사용자 이름 / 암호가 loginForm에 바인드되지 않습니다.
따라서 loginForm을 HTML로 하드 코딩하고 js / jquery를 사용하여 loginForm을 동적으로 이동 / 표시 / 숨겨야했습니다.
비고 : 아약스 로그인을하는 경우 autocomplete='off'
와 같은 태그 형태로 추가하지 마십시오
<form id='loginForm' action='signedIn.xxx' autocomplete='off'>
autocomplete='off'
사용자 이름 / 암호를 '자동 완성'하도록 허용하지 않기 때문에 loginForm에 사용자 이름 / 암호 복원이 실패합니다.
버튼 을 사용 하여 로그인 :
당신은을 사용하는 경우 type="button"
로 onclick
사용하여 로그인 처리기 ajax
, 다음 브라우저가 제공하지 않습니다 암호를 저장합니다.
<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>
이 양식 에는 제출 단추 가없고 조치 필드가 없으므로 브라우저는 비밀번호 저장을 제공하지 않습니다.
제출 버튼을 사용 하여 로그인 :
그러나 단추를 변경하여 type="submit"
제출을 처리하면 브라우저는 비밀번호 저장 을 제안 합니다.
<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>
이 방법을 사용하면 브라우저는 비밀번호 저장을 제공해야합니다.
두 가지 방법 모두에 사용되는 Javascript 는 다음과 같습니다 .
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
}
나는 이것으로 스스로 고투하고 있었고, 마침내 문제와 실패 원인을 추적 할 수있었습니다.
그것은 모두 내 로그인 양식이 페이지에 동적으로 주입되었다는 사실에서 비롯되었습니다 (backbone.js 사용). 로그인 양식을 index.html 파일에 직접 삽입하자마자 모든 것이 매력처럼 작동했습니다.
브라우저가 기존의 로그인 양식이 있다는 것을 알고 있어야하기 때문이라고 생각하지만 내 페이지에 동적으로 주입 된 이후 "실제"로그인 양식이 존재한다는 것을 몰랐습니다.
이 솔루션은 Eric이 코딩 포럼에 게시 한 것을 위해 일했습니다.
메시지가 표시되지 않는 이유는 브라우저가 서버로 다시 새로 고치기 위해 페이지를 물리적으로 만들어야하기 때문입니다. 당신이 할 수있는 작은 트릭은 양식으로 두 가지 작업을 수행하는 것입니다. 첫 번째 조치는 Ajax 코드를 호출하여 제출하는 것입니다. 또한 양식이 숨겨진 iframe을 대상으로합니다.
암호:
<iframe src="ablankpage.htm" id="temp" name="temp" style="display:none"></iframe>
<form target="temp" onsubmit="yourAjaxCall();">
프롬프트가 나타나는지 확인하십시오.
에릭
http://www.codingforums.com/showthread.php?t=123007에 게시 됨
모든 브라우저 (chrome 25, safari 5.1, IE10, Firefox 16)에서 jQuery 및 ajax 요청을 사용하여 비밀번호를 저장하도록 요청 하는 궁극적 인 솔루션 이 있습니다 .
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>
요령은 양식을 중지하여 자체 방식 (event.stopPropagation ())을 제출하는 대신 자신의 코드 ($ .ajax ())를 보내고 ajax의 성공 콜백에서 양식을 다시 제출하여 브라우저가 양식을 잡아서 표시합니다. 비밀번호 저장 요청. 오류 처리기 등을 추가 할 수도 있습니다.
누군가에게 도움이되기를 바랍니다.
spetson의 답변을 시도했지만 Chrome 18에서는 작동하지 않았습니다. 효과는 iframe에로드 핸들러를 추가하고 제출을 방해하지 않는 것입니다 (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();
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 ()는 AJAX 호출을 수행하고 실패하면 loginForm div를 표시합니다. 사용자가 인증되지 않은 경우 웹 서비스는 403을 반환합니다.
FF 및 IE8에서도 작동하도록 테스트되었습니다.
브라우저가 양식이 로그인 양식임을 감지하지 못할 수 있습니다. 이 이전 질문 에 대한 논의에 따르면 , 브라우저는 다음과 같은 양식 필드를 찾습니다 <input type="password">
. 비밀번호 양식 필드가 이와 비슷한가요?
편집 : 아래 질문에 대답하기 위해 Firefox는 form.elements[n].type == "password"
(모든 양식 요소를 반복 하여) 암호 를 감지 한 다음 암호 필드 바로 앞에 텍스트 필드의 양식 요소를 통해 뒤로 검색하여 사용자 이름 필드를 감지 한다고 생각 합니다 (자세한 내용은 여기 ). 내가 알 수 있듯이 귀하의 로그인 양식은 <form>
Firefox의 일부 이거나 Firefox가 감지하지 못합니다.
나는이 스레드에서 다양한 답변을 읽는 데 많은 시간을 보냈으며 실제로는 약간 다른 (관련되어 있지만 다른) 것이 었습니다. 모바일 Safari (iOS 장치)에서 페이지가로드 될 때 로그인 양식이 숨겨져 있으면 양식을 표시 한 후 제출 한 후 프롬프트가 표시되지 않습니다. 페이지로드 후 5 초 후에 양식을 표시하는 다음 코드로 테스트 할 수 있습니다. JS와 디스플레이를 제거하십시오 : none 및 작동합니다. 나는 다른 사람이 같은 문제가 있고 원인을 알 수없는 경우를 대비하여 아직 이것에 대한 해결책을 찾지 못했습니다.
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>
다음 코드가 테스트되었습니다
- Chrome 39.0.2171.99m : 작동 중
- 안드로이드 크롬 39.0.2171.93 : 작동
- Android 주식 브라우저 (Android 4.4) : 작동하지 않음
- Internet Explorer 5 이상 (에뮬레이트 됨) : 작동 중
- Internet Explorer 11.0.9600.17498 / 업데이트 버전 : 11.0.15 : 작동
- Firefox 35.0 : 작동
JS- 피들 :
http://jsfiddle.net/ocozggqu/
우편 번호 :
// modified post-code from https://stackoverflow.com/questions/133925/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
}
비고
- 동적 로그인 양식의 경우 호출
window.external.AutoCompleteSaveForm
이 필요합니다 - Internet Explorer 에는 상점 암호 대화 상자를 표시하기 위해 "암호"필드가 필요합니다.
- Internet Explorer는 제출 단추를 클릭해야합니다 (가짜 클릭 인 경우에도)
다음은 샘플 ajax 로그인 코드입니다.
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
});
};
비고
- "계정 / 로그인"은 성공 하면 쿠키를 설정합니다
- 페이지 리디렉션 ( "수동으로"js-code에 의해 시작됨)이 필요한 것 같습니다. 또한 iframe-post를 테스트했지만 성공하지 못했습니다.
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.
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]
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();
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).
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. :-)
The truth is, you can't force the browser to ask. I'm sure the browser has it's own algorithm for guessing if you've entered a username/password, such as looking for an input of type="password"
but you cannot set anything to force the browser.
You could, as others suggest, add user information in a cookie. If you do this, you better encrypt it at the least and do not store their password. Perhaps store their username at most.
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.
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>
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.
참고URL : https://stackoverflow.com/questions/2382329/how-can-i-get-browser-to-prompt-to-save-password
'Programing' 카테고리의 다른 글
github에서 풀 요청을 취소하는 방법은 무엇입니까? (0) | 2020.06.29 |
---|---|
std :: array를 사용하여 C 배열 초기화 "int arr [] = {e1, e2, e3,…}"동작을 에뮬레이트하는 방법? (0) | 2020.06.29 |
ORA-12505, TNS : listener가 현재 연결 설명자에 제공된 SID를 알지 못합니다. (0) | 2020.06.28 |
C #을 사용한 압축 / 압축 해제 문자열 (0) | 2020.06.28 |
Xcode 4에서 탭 사이를 빠르게 전환하는 방법은 무엇입니까 (0) | 2020.06.28 |