브라우저 자동 채우기 검출
브라우저가 텍스트 상자를 자동으로 채웠는지 어떻게 알 수 있습니까?특히 페이지 로드 주위에 자동 입력되는 사용자 이름 및 비밀번호 상자에 적합합니다.
첫 번째 질문은 페이지 로드 시퀀스에서 언제 이런 일이 발생합니까?문서 작성 전입니까, 후입니까?준비 완료입니까?
둘째, 이 문제가 발생했는지 확인하기 위해 어떻게 논리를 사용할 수 있습니까?이런 일이 일어나는 걸 막고 싶은 게 아니라 이벤트에 참여하세요.바람직한 것은 다음과 같습니다.
if (autoFilled == true) {
} else {
}
가능하다면 당신의 답변을 보여주는 jsfiddle을 보고 싶습니다.
중복 가능성
브라우저 암호 자동 채우기에 대한 DOM 이벤트입니까?
브라우저 자동 채우기 및 Javascript 트리거 이벤트
--이 두 질문 모두 실제로 어떤 이벤트가 트리거되는지 설명하는 것이 아니라 텍스트 상자를 계속 재체크합니다(성능에 좋지 않습니다.
문제는 브라우저마다 자동 채우기가 다르게 처리된다는 것입니다.변경 이벤트를 디스패치하는 사람도 있고 그렇지 않은 사람도 있습니다.따라서 브라우저가 입력 필드를 자동 완성할 때 트리거되는 이벤트에 연결하는 것은 거의 불가능합니다.
다른 브라우저의 이벤트 트리거 변경:
사용자 이름/비밀번호 필드의 경우:
- Firefox 4, IE 7, 및 IE 8은 변경 이벤트를 디스패치하지 않습니다.
- Safari 5 및 Chrome 9는 변경 이벤트를 디스패치합니다.
기타 양식 필드의 경우:
- IE 7 및 IE 8은 변경 이벤트를 디스패치하지 않습니다.
- Firefox 4는 사용자가 제안 목록에서 값을 선택하고 필드 밖에서 탭을 누르면 변경 변경 이벤트를 디스패치합니다.
- Chrome 9는 변경 이벤트를 디스패치하지 않는다.
- Safari 5는 변경 이벤트를 디스패치한다.
에 대해 하지 않도록 설정하는 입니다.autocomplete="off"
폼 또는 정기적으로 폴링하여 채워졌는지 확인합니다.
document.ready에 입력되어 있는지, 또는 그 전에 입력되어 있는지에 대한 질문은 브라우저마다, 심지어 버전마다 다릅니다.username/password 필드의 경우 [username password]필드가 채워집니다.따라서 어떤 이벤트에든 첨부하려고 하면 매우 지저분한 코드를 갖게 됩니다.
여기서 잘 읽어보실 수 있습니다.
WebKit 브라우저용 솔루션
:-webkit-autofill CSS 유사 클래스의 MDN 문서에서 다음 절차를 수행합니다.
:-webkit-autofill CSS 유사 클래스는 요소가 브라우저에 의해 값이 자동 채워졌을 때 일치합니다.
원하는 void transition css 규칙을 정의할 수 있습니다.<input>
가 되면:-webkit-autofill
가 할 수 있습니다. JS는 JS에 있습니다.animationstart
Clarna UI 팀 크레딧입니다.이 제품의 뛰어난 실장은 이쪽에서 확인하실 수 있습니다.
이것은 최신 Firefox, Chrome 및 Edge에서 작동합니다.
$('#email').on('blur input', function() {
....
});
저는 이 문제에 대해 많이 읽고 있었고, 도움이 되는 매우 빠른 해결 방법을 제공하고 싶었습니다.
let style = window.getComputedStyle(document.getElementById('email'))
if (style && style.backgroundColor !== inputBackgroundNormalState) {
this.inputAutofilledByBrowser = true
}
서 ''는inputBackgroundNormalState
'(255, 255, 255)'이다.
따라서 기본적으로 브라우저는 자동완료를 적용하면 입력에 다른 노란색(어노이징)을 적용함으로써 입력이 자동으로 채워진다는 것을 나타내는 경향이 있습니다.
Edit : 모든 브라우저에서 동작합니다.
Google Chrome 자동 완성에서는 다음과 같이 동작했습니다.
if ($("#textbox").is(":-webkit-autofill"))
{
// the value in the input field of the form was filled in with google chrome autocomplete
}
(오늘과 마찬가지로) 누군가가 브라우저의 자동 채우기 변경을 듣기 위해 솔루션을 찾고 있는 경우를 위해, 제가 작성한 커스텀 jquery 메서드는 다음과 같습니다.변경 리스너를 입력에 추가할 때 프로세스를 단순화하기 위해서입니다.
$.fn.allchange = function (callback) {
var me = this;
var last = "";
var infunc = function () {
var text = $(me).val();
if (text != last) {
last = text;
callback();
}
setTimeout(infunc, 100);
}
setTimeout(infunc, 100);
};
다음과 같이 말할 수 있습니다.
$("#myInput").allchange(function () {
alert("change!");
});
또한 라벨이 자동 필을 검출하지 못하고 텍스트 채우기 시 라벨 이동 애니메이션이 겹치는 같은 문제에 직면했고, 이 해결방법은 나에게 효과가 있었습니다.
input:-webkit-autofill ~ label {
top:-20px;
}
유감스럽게도 이 크로스 브라우저를 확인할 수 있는 유일한 방법은 입력을 폴링하는 것입니다.반응성을 높이기 위해 이벤트도 듣습니다.크롬은 해킹이 필요한 Javascript에서 자동 채우기 값을 숨기기 시작했습니다.
- 0.5~3초 간격으로 폴링합니다(대부분의 경우 즉시 폴링할 필요는 없습니다).
- JQuery를 사용하여 변경 이벤트를 트리거한 후 변경 이벤트를 청취하는 함수에서 논리를 수행합니다.
Chrome 숨겨진 자동 채우기 암호 값에 대한 수정을 추가합니다.
$(document).ready(function () { $('#inputID').change(YOURFUNCTIONNAME); $('#inputID').keypress(YOURFUNCTIONNAME); $('#inputID').keyup(YOURFUNCTIONNAME); $('#inputID').blur(YOURFUNCTIONNAME); $('#inputID').focusin(YOURFUNCTIONNAME); $('#inputID').focusout(YOURFUNCTIONNAME); $('#inputID').on('input', YOURFUNCTIONNAME); $('#inputID').on('textInput', YOURFUNCTIONNAME); $('#inputID').on('reset', YOURFUNCTIONNAME); window.setInterval(function() { var hasValue = $("#inputID").val().length > 0;//Normal if(!hasValue){ hasValue = $("#inputID:-webkit-autofill").length > 0;//Chrome } if (hasValue) { $('#inputID').trigger('change'); } }, 333); });
솔루션:
change
DOM 컨텐츠 로드 시, 통상의 이벤트와 같이 다음의 조작을 실시합니다.
setTimeout(function() {
$('input').each(function() {
var elem = $(this);
if (elem.val()) elem.change();
})
}, 250);
사용자가 필드를 편집하기 전에 비어 있지 않은 모든 필드에 대한 변경 이벤트가 발생합니다.
github에는 이 문제를 해결하기 위한 새로운 폴리필 컴포넌트가 있습니다.자동 채우기 이벤트를 보십시오.설치만 하면 됩니다.오토필은 예상대로 동작합니다.
bower install autofill-event
저도 비슷한 걸 찾고 있었어요.Chrome만...내 경우 래퍼 div는 입력 필드가 자동으로 채워졌는지 알아야 합니다.따라서 Chrome이 자동 입력 시 입력 필드에 추가 css를 부여할 수 있습니다.위의 모든 답변을 살펴보면 다음과 같습니다.
/*
* make a function to use it in multiple places
*/
var checkAutoFill = function(){
$('input:-webkit-autofill').each(function(){
$(this).closest('.input-wrapper').addClass('autofilled');
});
}
/*
* Put it on the 'input' event
* (happens on every change in an input field)
*/
$('html').on('input', function() {
$('.input-wrapper').removeClass('autofilled');
checkAutoFill();
});
/*
* trigger it also inside a timeOut event
* (happens after chrome auto-filled fields on page-load)
*/
setTimeout(function(){
checkAutoFill();
}, 0);
이 기능을 하기 위한 html은 다음과 같습니다.
<div class="input-wrapper">
<input type="text" name="firstname">
</div>
다음은 Klarna UI 팀에서 가져온 CSS 솔루션입니다.구현에 대한 자세한 내용은 여기를 참조하십시오.
난 괜찮아.
input:-webkit-autofill {
animation-name: onAutoFillStart;
transition: background-color 50000s ease-in-out 0s;
}
input:not(:-webkit-autofill) {
animation-name: onAutoFillCancel;
}
나는 이것이 오래된 실이라는 것을 알지만 많은 사람들이 이 문제에 대한 해결책을 찾기 위해 여기에 올 것이라고 상상할 수 있다.
이를 위해 입력에 다음과 같은 값이 있는지 여부를 확인할 수 있습니다.
$(function() {
setTimeout(function() {
if ($("#inputID").val().length > 0) {
// YOUR CODE
}
}, 100);
});
송신 버튼을 유효하게 하기 위해서, 로그인 폼이 로드되었을 때에, 스스로 로그인 폼의 값을 확인합니다.코드는 jQuery용으로 만들어졌지만 필요에 따라 쉽게 변경할 수 있습니다.
Chrome에서는 자동 입력 요소에 대한 특별한 css 규칙을 설정하고 요소에 해당 규칙이 적용되었는지 javascript를 사용하여 확인함으로써 자동 입력 필드를 검출할 수 있습니다.
예를 들어:
CSS
input:-webkit-autofill {
-webkit-box-shadow: 0 0 0 30px white inset;
}
자바스크립트
let css = $("#selector").css("box-shadow")
if (css.match(/inset/))
console.log("autofilled:", $("#selector"))
이것은 웹킷 렌더 엔진을 탑재한 브라우저용 솔루션입니다.폼이 자동 입력되면 입력은 유사 클래스 :-webkit-autofill-(f. 입력:-webkit-autofill {...)을 가져옵니다.}) JavaScript에서 확인해야 하는 식별자입니다.
테스트 폼이 있는 솔루션:
<form action="#" method="POST" class="js-filled_check">
<fieldset>
<label for="test_username">Test username:</label>
<input type="text" id="test_username" name="test_username" value="">
<label for="test_password">Test password:</label>
<input type="password" id="test_password" name="test_password" value="">
<button type="submit" name="test_submit">Test submit</button>
</fieldset>
</form>
javascript:
$(document).ready(function() {
setTimeout(function() {
$(".js-filled_check input:not([type=submit])").each(function (i, element) {
var el = $(this),
autofilled = (el.is("*:-webkit-autofill")) ? el.addClass('auto_filled') : false;
console.log("element: " + el.attr("id") + " // " + "autofilled: " + (el.is("*:-webkit-autofill")));
});
}, 200);
});
페이지가 로드될 때 발생하는 문제는 패스워드 값, 짝수 길이입니다.이는 브라우저의 보안 때문입니다.또한 시간 초과는 브라우저가 일정 시간 후에 폼을 채우기 때문입니다.
이 코드는 채워진 입력에 auto_filled 클래스를 추가합니다.또, 입력 타입의 패스워드 값이나 길이를 확인하려고 했습니다만, 페이지의 이벤트가 발생한 직후에 동작합니다.그래서 어떤 이벤트를 시작하려고 했지만, 성공하지 못했어요.지금은 이게 내 해결책이야.맛있게 드세요!
이 질문에 대한 완벽한 해결책이 있습니다. 이 코드 조각을 사용해 보십시오.
★★★★★★★★★★★★★★★★.
function ModernForm() {
var modernInputElement = $('.js_modern_input');
function recheckAllInput() {
modernInputElement.each(function() {
if ($(this).val() !== '') {
$(this).parent().find('label').addClass('focus');
}
});
}
modernInputElement.on('click', function() {
$(this).parent().find('label').addClass('focus');
});
modernInputElement.on('blur', function() {
if ($(this).val() === '') {
$(this).parent().find('label').removeClass('focus');
} else {
recheckAllInput();
}
});
}
ModernForm();
.form_sec {
padding: 30px;
}
.form_sec .form_input_wrap {
position: relative;
}
.form_sec .form_input_wrap label {
position: absolute;
top: 25px;
left: 15px;
font-size: 16px;
font-weight: 600;
z-index: 1;
color: #333;
-webkit-transition: all ease-in-out 0.35s;
-moz-transition: all ease-in-out 0.35s;
-ms-transition: all ease-in-out 0.35s;
-o-transition: all ease-in-out 0.35s;
transition: all ease-in-out 0.35s;
}
.form_sec .form_input_wrap label.focus {
top: 5px;
color: #a7a9ab;
font-weight: 300;
-webkit-transition: all ease-in-out 0.35s;
-moz-transition: all ease-in-out 0.35s;
-ms-transition: all ease-in-out 0.35s;
-o-transition: all ease-in-out 0.35s;
transition: all ease-in-out 0.35s;
}
.form_sec .form_input {
width: 100%;
font-size: 16px;
font-weight: 600;
color: #333;
border: none;
border-bottom: 2px solid #d3d4d5;
padding: 30px 0 5px 0;
outline: none;
}
.form_sec .form_input.err {
border-bottom-color: #888;
}
.form_sec .cta_login {
border: 1px solid #ec1940;
border-radius: 2px;
background-color: #ec1940;
font-size: 14px;
font-weight: 500;
text-align: center;
color: #ffffff;
padding: 15px 40px;
margin-top: 30px;
display: inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form class="form_sec">
<div class="row clearfix">
<div class="form-group col-lg-6 col-md-6 form_input_wrap">
<label>
Full Name
</label>
<input type="text" name="name" id="name" class="form_input js_modern_input">
</div>
</div>
<div class="row clearfix">
<div class="form-group form_input_wrap col-lg-6 col-md-6">
<label>
Emaill
</label>
<input type="email" name="email" class="form_input js_modern_input">
</div>
</div>
<div class="row clearfix">
<div class="form-group form_input_wrap col-lg-12 col-md-12">
<label>
Address Line 1
</label>
<input type="text" name="address" class="form_input js_modern_input">
</div>
</div>
<div class="row clearfix">
<div class="form-group col-lg-6 col-md-6 form_input_wrap">
<label>
City
</label>
<input type="text" name="city" class="form_input js_modern_input">
</div>
<div class="form-group col-lg-6 col-md-6 form_input_wrap">
<label>
State
</label>
<input type="text" name="state" class="form_input js_modern_input">
</div>
</div>
<div class="row clearfix">
<div class="form-group col-lg-6 col-md-6 form_input_wrap">
<label>
Country
</label>
<input type="text" name="country" class="form_input js_modern_input">
</div>
<div class="form-group col-lg-4 col-md-4 form_input_wrap">
<label>
Pin
</label>
<input type="text" name="pincode" class="form_input js_modern_input">
</div>
</div>
<div class="row cta_sec">
<div class="col-lg-12">
<button type="submit" class="cta_login">Submit</button>
</div>
</div>
</form>
및 Edge에서 Chrome 및 Edge(2020)를 합니다.:-webkit-autofill
이치노그러나 사용자가 어떤 방식으로 페이지와 대화할 때까지 JavaScript는 입력 값을 가져올 수 없습니다.
「」를 사용합니다.$('x').focus()
★★★★★★★★★★★★★★★★★」$('x').blur()
코드로 마우스 이벤트를 발생시키는 것은 도움이 되지 않습니다.
https://stackoverflow.com/a/35783761/32429 를 참조해 주세요.
2020년, 크롬은 이렇게 작동했습니다.
// wait 0.1 sec to execute action after detecting autofill
// check if input username is autofilled by browser
// enable "login" button for click to submit form
$(window).on("load", function(){
setTimeout(function(){
if ($("#UserName").is("input:-webkit-autofill"))
$("#loginbtn").prop('disabled', false);
}, 100);
});
브라우저가 입력을 채우고 있는지 아닌지를 이해하기 위한 요령이 있습니다(부울).
const inputEl = inputRef.current; // select the el with any way, here is ReactJs ref
let hasValue;
try {
hasValue = inputRef.current.matches(':autofill');
} catch (err) {
try {
hasValue = inputRef.current.matches(':-webkit-autofill');
} catch (er) {
hasValue = false;
}
}
// hasValue (boolean) is ready
에 '''가 붙는다'''hasValue
발생했는지 할 수 .브라우저 자동 채우기가 발생했는지 여부를 감지할 수 있습니다.
첫 페이지 로드 시 자동 채우기 입력을 검출하는 문제를 몇 시간 동안 해결하여 Chrome, Opera, Edge 및 FF에서도 사용할 수 있는 이상적인 솔루션을 찾았습니다.
크롬, 오페라, 엣지 문제는 꽤 EZ로 해결되었다.
유사 클래스로 요소를 검색하여input:-webkit-autofill
원하는 작업을 수행합니다(내 경우 입력 래퍼 클래스를 변경하여 플로트 라벨 패턴으로 라벨 위치를 변경합니다).
Firefox에서 문제가 발생하였습니다.
왜냐하면 FF에는 단순히 DOM을 검색하기만 하면 볼 수 있는 의사 클래스 또는 유사한 클래스(많은 사람이 ":-moz-autofill"을 제안함)가 없기 때문입니다.노란색 입력 배경도 찾을 수 없습니다.유일한 원인은 브라우저가 필터 속성을 변경하여 다음 노란색을 추가하는 것입니다.
input:-moz-autofill, input:-moz-autofill-preview { filter: grayscale(21%) brightness(88%) contrast(161%) invert(10%) sepia(40%) saturate(206%); }
따라서 Firefox의 경우 먼저 모든 입력을 검색하여 계산된 스타일을 얻은 다음 브라우저 설정에서 하드코딩된 이 필터 스타일과 비교해야 합니다.나는 그들이 왜 단순한 배경색을 사용하지 않고 그 이상한 필터를 사용했는지 정말 모르겠다!?그들은 삶을 더 힘들게 한다;)
다음은 제 웹사이트(https://my.oodo.pl/en/modules/register/login.php)에서 마법처럼 작동하는 코드입니다.
<script type="text/javascript">
/*
* this is my main function
*/
var checkAutoFill = function(){
/*first we detect if we have FF or other browsers*/
var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
if (!isFirefox) {
$('input:-webkit-autofill').each(function(){
/*here i have code that adds "focused" class to my input wrapper and changes
info instatus div. U can do what u want*/
$(this).closest('.field-wrapper').addClass('focused');
document.getElementById("status").innerHTML = "Your browser autofilled form";
});
}
if (isFirefox) {
$('input').each(function(){
var bckgrnd = window.getComputedStyle(document.getElementById(this.id), null).getPropertyValue("background-image");
if (bckgrnd === 'linear-gradient(rgba(255, 249, 145, 0.5), rgba(255, 249, 145, 0.5))') {
/*if our input has that filter property customized by browserr with yellow background i do as above (change input wrapper class and change status info. U can add your code here)*/
$(this).closest('.field-wrapper').addClass('focused');
document.getElementById("status").innerHTML = "Your Browser autofilled form";
}
})
}
}
/*im runing that function at load time and two times more at 0.5s and 1s delay because not all browsers apply that style imediately (Opera does after ~300ms and so Edge, Chrome is fastest and do it at first function run)*/
checkAutoFill();
setTimeout(function(){
checkAutoFill();
}, 500);
setTimeout(function(){
checkAutoFill();
}, 1000);
})
</script>
당신에게 중요하지 않은 쓰레기를 버리기 위해 위 코드를 수동으로 편집했습니다.사용자가 사용할 수 없는 경우 IDE에 붙여넣고 구문을 다시 확인하십시오.) 물론 디버깅경보 또는 콘솔로그를 추가하여 커스터마이즈합니다.
저는 이 용액을 같은 문제에 사용했습니다.
HTML 코드는 다음과 같이 변경됩니다.
<input type="text" name="username" />
<input type="text" name="password" id="txt_password" />
jQuery 코드가 입력되어 있어야 합니다.document.ready
:
$('#txt_password').focus(function(){
$(this).attr('type','password');
});
pwd 필드가 자동으로 입력되었는지 확인하기 위해 사용자 이름으로 blur 이벤트를 사용했습니다.
$('#userNameTextBox').blur(function () {
if ($('#userNameTextBox').val() == "") {
$('#userNameTextBox').val("User Name");
}
if ($('#passwordTextBox').val() != "") {
$('#passwordTextBoxClear').hide(); // textbox with "Password" text in it
$('#passwordTextBox').show();
}
});
이것은 IE에서 동작하며, 다른 모든 브라우저에서도 동작합니다(IE만 확인했습니다).
저도 같은 문제가 있어서 이 해결책을 썼습니다.
페이지 로드 시 모든 입력 필드에서 폴링이 시작됩니다(10초 설정했지만 이 값을 조정할 수 있습니다).
10초 후에 모든 입력 필드에서 폴링을 정지하고 집중 입력(있는 경우)에만 폴링을 시작합니다.입력을 흐리게 하면 멈추고 초점을 맞추면 다시 시작합니다.
이 방법에서는 정말로 필요한 경우에만 유효한 입력에 대해서만 폴링을 실시합니다.
// This part of code will detect autofill when the page is loading (username and password inputs for example)
var loading = setInterval(function() {
$("input").each(function() {
if ($(this).val() !== $(this).attr("value")) {
$(this).trigger("change");
}
});
}, 100);
// After 10 seconds we are quite sure all the needed inputs are autofilled then we can stop checking them
setTimeout(function() {
clearInterval(loading);
}, 10000);
// Now we just listen on the focused inputs (because user can select from the autofill dropdown only when the input has focus)
var focused;
$(document)
.on("focus", "input", function() {
var $this = $(this);
focused = setInterval(function() {
if ($this.val() !== $this.attr("value")) {
$this.trigger("change");
}
}, 100);
})
.on("blur", "input", function() {
clearInterval(focused);
});
여러 개의 값을 자동으로 삽입하면 제대로 작동하지 않지만 현재 양식에서 모든 입력을 검색하여 조정할 수 있습니다.
예를 들어 다음과 같습니다.
// This part of code will detect autofill when the page is loading (username and password inputs for example)
var loading = setInterval(function() {
$("input").each(function() {
if ($(this).val() !== $(this).attr("value")) {
$(this).trigger("change");
}
});
}, 100);
// After 10 seconds we are quite sure all the needed inputs are autofilled then we can stop checking them
setTimeout(function() {
clearInterval(loading);
}, 10000);
// Now we just listen on inputs of the focused form
var focused;
$(document)
.on("focus", "input", function() {
var $inputs = $(this).parents("form").find("input");
focused = setInterval(function() {
$inputs.each(function() {
if ($(this).val() !== $(this).attr("value")) {
$(this).trigger("change");
}
});
}, 100);
})
.on("blur", "input", function() {
clearInterval(focused);
});
자동 채우기가 사용된 시기와 필드를 정확하게 감지하지 않고 자동 채우기가 사용되었는지 여부만 감지하려면 자동 채우기를 수행할 숨겨진 요소를 추가한 다음 여기에 값이 포함되어 있는지 확인합니다.이것이 많은 사람들이 관심을 갖는 것이 아닐 수도 있다는 것을 이해한다.입력 필드를 음의 탭인덱스와 화면에서 멀리 떨어진 절대 좌표로 설정합니다.입력이 나머지 입력과 동일한 형식의 일부인 것이 중요합니다.자동 채우기로 선택되는 이름을 사용해야 합니다(예:"second name" (세컨드 네임)
var autofilldetect = document.createElement('input');
autofilldetect.style.position = 'absolute';
autofilldetect.style.top = '-100em';
autofilldetect.style.left = '-100em';
autofilldetect.type = 'text';
autofilldetect.name = 'secondname';
autofilldetect.tabIndex = '-1';
이 입력을 양식에 추가하고 양식 제출 시 해당 값을 확인합니다.
폴링에 의존하지 않는 솔루션이 있는 것 같습니다(적어도 Chrome의 경우).그것은 거의 해킹에 가깝지만, 나는 글로벌 여론 조사보다 약간 낫다고 생각한다.
다음 시나리오를 고려합니다.
사용자가 필드 1을 입력하기 시작합니다.
사용자가 필드 2 및 필드 3을 자동 채울 자동 완성 제안을 선택합니다.
솔루션:다음 jQuery 스니펫 $(':-webkit-autofill')를 통해 자동 입력된 필드가 있는지 확인하는 모든 필드에 onblur를 등록합니다.
이는 사용자가 field1을 블러할 때까지 지연되기 때문에 즉각적이지는 않지만 글로벌 폴링에 의존하지 않기 때문에 IMO가 더 나은 솔루션입니다.
즉, Enter 키를 누르면 폼이 송신되기 때문에, onkey press에 대응하는 핸들러가 필요하게 되는 경우가 있습니다.
또는 글로벌 폴링을 사용하여 $(':-webkit-autofill')를 체크할 수 있습니다.
제 개인적인 경험상 아래 코드는 파이어폭스 IE나 사파리에서는 잘 작동하지만 크롬에서는 자동완성을 선택하는 것은 잘 되지 않습니다.
function check(){
clearTimeout(timeObj);
timeObj = setTimeout(function(){
if($('#email').val()){
//do something
}
},1500);
}
$('#email').bind('focus change blur',function(){
check();
});
아래 코드는 사용자가 입력 필드를 클릭할 때마다 트리거되므로 더 잘 작동합니다. 여기서 입력 필드가 비어 있는지 여부를 확인할 수 있습니다.
$('#email').bind('click', function(){
check();
});
크롬을 사용하여 성공했습니다.
setTimeout(
function(){
$("#input_password").focus();
$("#input_username").focus();
console.log($("#input_username").val());
console.log($("#input_password").val());
}
,500);
솔루션은 다음과 같습니다.
$.fn.onAutoFillEvent = function (callback) {
var el = $(this),
lastText = "",
maxCheckCount = 10,
checkCount = 0;
(function infunc() {
var text = el.val();
if (text != lastText) {
lastText = text;
callback(el);
}
if (checkCount > maxCheckCount) {
return false;
}
checkCount++;
setTimeout(infunc, 100);
}());
};
$(".group > input").each(function (i, element) {
var el = $(element);
el.onAutoFillEvent(
function () {
el.addClass('used');
}
);
});
조사 결과 웹킷브라우저가 자동완료 시 변경 이벤트를 발생시키지 않는 것이 문제입니다.제 해결책은 웹킷이 추가하는 자동 채우기 클래스를 직접 받아서 변경 이벤트를 트리거하는 것이었습니다.
setTimeout(function() {
if($('input:-webkit-autofill').length > 0) {
//do some stuff
}
},300)
여기 크롬에 관한 문제의 링크가 있습니다.https://bugs.chromium.org/p/chromium/issues/detail?id=636425
Firefox에서 자동 채우기를 감지하는 데 어려움을 겪었습니다.이 솔루션만이 유효했습니다.
HTML:
<div class="inputFields">
<div class="f_o">
<div class="field_set">
<label class="phold">User</label>
<input type="tel" class="form_field " autocomplete="off" value="" maxlength="50">
</div>
</div>
<div class="f_o">
<div class="field_set">
<label class="phold">Password</label>
<input type="password" class="form_field " autocomplete="off" value="" maxlength="50">
</div>
</div>
</div>
CSS:
/* Detect autofill for Chrome */
.inputFields input:-webkit-autofill {
animation-name: onAutoFillStart;
transition: background-color 50000s ease-in-out 0s;
}
.inputFields input:not(:-webkit-autofill) {
animation-name: onAutoFillCancel;
}
@keyframes onAutoFillStart {
}
@keyframes onAutoFillCancel {
}
.inputFields {
max-width: 414px;
}
.field_set .phold{
display: inline-block;
position: absolute;
font-size: 14px;
color: #848484;
-webkit-transform: translate3d(0,8px,0);
-ms-transform: translate3d(0,8px,0);
transform: translate3d(0,8px,0);
-webkit-transition: all 200ms ease-out;
transition: all 200ms ease-out;
background-color: transparent;
-webkit-backface-visibility: hidden;
backface-visibility: hidden;
margin-left: 8px;
z-index: 1;
left: 0;
pointer-events: none;
}
.field_set .phold_active {
font-size: 12px;
-webkit-transform: translate3d(0,-8px,0);
-ms-transform: translate3d(0,-8px,0);
transform: translate3d(0,-8px,0);
background-color: #FFF;
padding-left: 3px;
padding-right: 3px;
}
.field_set input[type='text'], .field_set select, .field_set input[type='tel'], .field_set input[type='password'] {
height: 36px;
}
.field_set input[type='text'], .field_set input[type='tel'], .field_set input[type='password'], .field_set select, .field_set textarea {
box-sizing: border-box;
width: 100%;
padding: 5px;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
border: 1px solid #ababab;
border-radius: 0;
}
.field_set {
margin-bottom: 10px;
position: relative;
}
.inputFields .f_o {
width: 100%;
line-height: 1.42857143;
float: none;
}
JavaScript:
// detect auto-fill when page is loading
$(window).on('load', function() {
// for sign in forms when the user name and password are filled by browser
getAutofill('.inputFields');
});
function getAutofill(parentClass) {
if ($(parentClass + ' .form_field').length > 0) {
var formInput = $(parentClass + ' .form_field');
formInput.each(function(){
// for Chrome: $(this).css('animation-name') == 'onAutoFillStart'
// for Firefox: $(this).val() != ''
if ($(this).css('animation-name') == 'onAutoFillStart' || $(this).val() != '') {
$(this).siblings('.phold').addClass('phold_active');
} else {
$(this).siblings('.phold').removeClass('phold_active');
}
});
}
}
$(document).ready(function(){
$(document).on('click','.phold',function(){
$(this).siblings('input, textarea').focus();
});
$(document).on('focus','.form_field', function(){
$(this).siblings('.phold').addClass('phold_active');
});
// blur for Chrome and change for Firefox
$(document).on('blur change','.form_field', function(){
var $this = $(this);
if ($this.val().length == 0) {
$(this).siblings('.phold').removeClass('phold_active');
} else {
$(this).siblings('.phold').addClass('phold_active');
}
});
// case when form is reloaded due to errors
if ($('.form_field').length > 0) {
var formInput = $('.form_field');
formInput.each(function(){
if ($(this).val() != '') {
$(this).siblings('.phold').addClass('phold_active');
} else {
$(this).siblings('.phold').removeClass('phold_active');
}
});
}
});
: Chrome 용: :if ($(this).css('animation-name') == 'onAutoFillStart')
Firefox™의 :if ($(this).val() != '')
언급URL : https://stackoverflow.com/questions/11708092/detecting-browser-autofill
'programing' 카테고리의 다른 글
왜 Math.floor는 더블을 반환합니까? (0) | 2022.11.03 |
---|---|
크롬에서는 잘 작동하지만 IE(인터넷 익스플로러)에서는 작동하지 않는다. (0) | 2022.11.03 |
Vue.JS "TypeError: reverseMessage가 함수가 아닙니다." (0) | 2022.11.03 |
PHP의 innode(' , , array_filter(array ))에 상당하는 Java (0) | 2022.11.03 |
jQuery를 사용하여 드롭다운 목록의 선택한 값 변경 (0) | 2022.11.03 |