Angularjs 크롬 자동 완성 딜레마
Chrome의 자동 완성 기능을 사용하지 않는 한, 간단한 로그인 폼이 있습니다.
입력을 시작하고 자동 완료 기능을 사용하면 암호가 자동으로 채워지는 경우 angularjs 모델에는 암호 값이 없습니다.
폼에 속성을 설정하여 자동 완료를 해제하려고 했습니다.autocomplete="off"효과가 없는 것 같아요.
다음 방법: 1. Chrome의 자동 완성 기능을 사용하는 경우 값을 얻을 수 있는지 확인합니까? 2. Chrome의 자동 완성 기능을 비활성화하시겠습니까?
<form class="form-signin" name="form" ng-submit="login()" autocomplete="off">
<h3>Login</h3>
<input type="email" name="email" class="form-control" placeholder="Email address" ng-model="user.email" required autofocus>
<input type="password" name="password" class="form-control" placeholder="Password" ng-model="user.password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
코멘트에 추가된 링크:Github의 문제
// Due to browsers issue, it's impossible to detect without a timeout any changes of autofilled inputs
// https://github.com/angular/angular.js/issues/1460
// https://github.com/angular/angular.js/issues/1460#issuecomment-28662156
// Could break future Angular releases (if use `compile()` instead of `link())
// TODO support select
angular.module("app").config(["$provide", function($provide) {
var inputDecoration = ["$delegate", "inputsWatcher", function($delegate, inputsWatcher) {
var directive = $delegate[0];
var link = directive.link;
function linkDecoration(scope, element, attrs, ngModel){
var handler;
// By default model.$viewValue is equals to undefined
if(attrs.type == "checkbox"){
inputsWatcher.registerInput(handler = function(){
var value = element[0].checked;
// By default element is not checked
if (value && ngModel.$viewValue !== value) {
ngModel.$setViewValue(value);
}
});
}else if(attrs.type == "radio"){
inputsWatcher.registerInput(handler = function(){
var value = attrs.value;
// By default element is not checked
if (element[0].checked && ngModel.$viewValue !== value) {
ngModel.$setViewValue(value);
}
});
}else{
inputsWatcher.registerInput(handler = function(){
var value = element.val();
// By default value is an empty string
if ((ngModel.$viewValue !== undefined || value !== "") && ngModel.$viewValue !== value) {
ngModel.$setViewValue(value);
}
});
}
scope.$on("$destroy", function(){
inputsWatcher.unregisterInput(handler);
});
// Exec original `link()`
link.apply(this, [].slice.call(arguments, 0));
}
// Decorate `link()` don't work for `inputDirective` (why?)
/*
directive.link = linkDecoration;
*/
// So use `compile()` instead
directive.compile = function compile(element, attrs, transclude){
return linkDecoration;
};
delete directive.link;
return $delegate;
}];
$provide.decorator("inputDirective", inputDecoration);
$provide.decorator("textareaDirective", inputDecoration);
//TODO decorate selectDirective (see binding "change" for `Single()` and `Multiple()`)
}]).factory("inputsWatcher", ["$interval", "$rootScope", function($interval, $rootScope){
var INTERVAL_MS = 500;
var promise;
var handlers = [];
function execHandlers(){
for(var i = 0, l = handlers.length; i < l; i++){
handlers[i]();
}
}
return {
registerInput: function registerInput(handler){
if(handlers.push(handler) == 1){
promise = $interval(execHandlers, INTERVAL_MS);
}
},
unregisterInput: function unregisterInput(handler){
handlers.splice(handlers.indexOf(handler), 1);
if(handlers.length == 0){
$interval.cancel(promise);
}
}
}
}]);
송신원:Developer.mozilla.org 문서 Turning_off_form_autocompletion
작성자가 자신이 아닌 다른 사용자에 대해 새로운 비밀번호를 지정할 수 있는 사용자 관리 페이지에서 비밀번호 필드가 자동으로 입력되는 것을 방지하려면 autocomplete="new-password"를 지정해야 합니다. 단, 아직 모든 브라우저에서 이 지원이 구현되지는 않았습니다.
그럼 어떻게 하면 좋을까요?
- 암호 필드에서 autocomplete="new-password"를 설정합니다.
- 사용자 이름 필드에서 autocomplete="off"를 설정합니다.
당신에게도 효과가 있기를 바랍니다. :)
여기 기재한 바와 같이 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
자동 완성 요청을 위한 Google Chrome UI는 입력 요소 및 입력 요소에서 자동 완성이 꺼짐으로 설정되었는지 여부에 따라 달라집니다.특히 폼에 자동완성이 off로 설정되어 있고 입력요소의 자동완성 필드가 설정되어 있지 않은 경우 사용자가 입력요소에 대한 자동필 제안을 요청하면 Chrome은 "이 폼에 대해 자동완성이 비활성화되었습니다."라는 메시지를 표시할 수 있습니다.한편 폼과 입력 요소가 모두 off로 설정되어 있는 경우 브라우저는 해당 메시지를 표시하지 않습니다.따라서 사용자 정의 자동 완성이 있는 각 입력에 대해 자동 완료를 꺼짐으로 설정해야 합니다.
양쪽에서 autocomplete="off"를 설정해야 합니다.form그리고.input
이건 앵글이랑은 관련이 없는 것 같아JS
같은 문제를 안고 jQuery를 사용하여 제출 시 가치를 얻는 매우 간단한 솔루션을 찾았습니다.컨트롤러에는 다음이 있습니다.
$scope.username = "";
$scope.password = "";
$scope.login = function(){
$scope.username = $("#username").val();
$scope.password = $("#password").val();
// Proceed as normal
};
검증 등을 할 필요가 있는 경우는 단점이 있습니다만, 그 이외의 경우는 작은 폼이라도 괜찮습니다.
전자 메일 필드 값을 확인하고 해당 필드의 값이 변경될 때마다 암호 필드에서 "변경" 이벤트를 트리거할 수 있습니다.이 이벤트는 해당 필드에서 모든 ng-model 매직을 트리거하고 모델을 업데이트합니다.
module.directive("autocompleteFor", function () {
return {
restrict: "A",
link: function ($scope, $element, $attrs) {
$scope.$watch($attrs.autocompleteFor, function () {
$element.triggerHandler("change");
})
}
}
});
이 명령어를 사용하면 다음과 같이 시나리오를 처리할 수 있습니다.
<input type="email" name="email" ng-model="user.email">
<input type="password" autocomplete-for="user.email" name="password" ng-model="user.password" required>
-----------------------------
입력에서 자동 완성/자동 채우기를 비활성화하려면 autocomplete="off" 대신 - autocomplete="false"를 입력하십시오.
아래의 지시가 나에게 효과가 있었다.간단하고 깔끔한 수정입니다.도움이 됐으면 좋겠네요!
기준: 각도지시어를 사용하여 JS 브라우저 자동 채우기 해결 방법
여기 제시된 다른 솔루션보다 훨씬 덜 진부하고 의미론적으로 견실한 솔루션이 있습니다.JS: VictorBlog.com
myApp.directive('formAutofillFix', function() {
return function(scope, elem, attrs) {
// Fixes Chrome bug: https://groups.google.com/forum/#!topic/angular/6NlucSskQjY
elem.prop('method', 'POST');
// Fix autofill issues where Angular doesn't know about auto-filled inputs
if(attrs.ngSubmit) {
setTimeout(function() {
elem.unbind('submit').submit(function(e) {
e.preventDefault();
elem.find('input, textarea, select').trigger('input').trigger('change').trigger('keydown');
scope.$apply(attrs.ngSubmit);
});
}, 0);
}
};
});
그런 다음 양식에 지시문을 첨부하기만 하면 됩니다.
<form ng-submit="submitLoginForm()" form-autofill-fix>
<div>
<input type="email" ng-model="email" ng-required />
<input type="password" ng-model="password" ng-required />
<button type="submit">Log In</button>
</div>
</form>
대체 솔루션은 폼 요소를 제거하고 대신 ng-form을 사용하면 모든 브라우저 간섭이 비활성화됩니다.
<div ng-form="yourFormName" class="form-signin" ng-submit="login()">
오래된 질문이지만, 어쨌든
저도 같은 문제에 부딪혀 작은 "핵" 솔루션이 있습니다.이 문제는 앱의 여러 곳에서 발생했기 때문에 재사용에 대한 지침을 작성했습니다.
module.directive("fakeAutocomplete", [
function () {
return {
restrict: "EA",
replace: true,
template: "<div><input/><input type=\"password\"/></div>",
link: function (scope, elem, attrs) {
elem.css({
"overflow": "hidden",
"width": "0px",
"height": "0px"
});
}
}
}
]);
덧붙이기만 하면
<fake-autocomplete></fake-autocomplete>
폼의 선두와 브라우저는 가짜 필드를 자동 완성해야 하는 필드로 탐지합니다. 말하면 단히 simply simply simply simply simply simplydisplay:none더 이상 작동하지 않는 것 같습니다. 테스트를 해봤습니다.
제 경우 형식과 입력에서 속성 autocomplete="off"를 설정합니다.
<form autocomplete="off">
<input type="text" autocomplete="off">
</form>
그것이 그 문제에 대한 훨씬 더 간단한 해결책이 될 수 있다.
- Angularjs는 값을 "확인"할 수 없습니다.
- DOM(jQuery)을 통해 값을 가져온 다음 Angularjs로 되돌립니다.
```
angular.module('someModule').directive('chromeAutofillHack', function()
{
return {
require: '^ngModel',
restrict: 'A',
priority: 500, // set higher priority then other custom directives
link: function(scope, element, attrs , ngModelCtrl)
{
ngModelCtrl.$parsers.unshift(function(email)
{
if (!email) { // only do this when angular think there is no value
email = $(element).val();
ngModel.$setViewValue(email);
}
return email;
});
}
};
});
```
--- 더 이상 관련이 없는 ---
다음 항목을 추가하여 자동 완성(이상하게도)을 비활성화할 수 있었습니다.
<form ... novalidate>
<input ... formnovalidate />
Chrome 35.0, Firefox 30.0, angular 1.2.18용 솔루션(패스워드 매니저를 사용한 로그인 페이지, autofill, angular 메서드 및 redirect):
브라우저는 사용자에게 패스워드 저장을 요구하는 타이밍을 어떻게 알 수 있습니까?
저는 결국 여기에서는 아직 볼 수 없는 다른 해결책을 갖게 되었습니다.제가 찾은 바로는 사용자가 페이지와 대화할 때까지 패스워드 값은 모델(또는 js api)에 노출되지 않습니다.로그인 버튼을 클릭하면 값을 사용할 수 있는 충분한 상호 작용이 있으며, 데이터 바인딩은 버튼의 클릭 핸들러가 모델에서 패스워드에 액세스 할 수 있을 정도로 충분히 빨리 성공합니다.브라우저가 자동으로 채워진 것을 감지하면 모델이 업데이트되지 않았더라도 로그인 버튼을 활성화할 수 있습니다.그래서 Chrome이 입력 내용을 자동으로 입력했는지 확인하기 위해 간단한 도우미 서비스를 작성했습니다.
utilApp.service('autoFillDetectionService', [function () {
return {
hasAutoFillInputs: function () {
try{
return !!$(':-webkit-autofill').length;
}
catch (x) {
// IE gets here, it/jquery complains about an invalid pseudo-class
return false;
}
}
};
}]);
로그인 컨트롤러에서는 입력 필드가 autofill로 마킹되어 있는지 여부를 인터벌 체크하고, 마킹되어 있는 경우는 login 버튼을 유효하게 합니다.
autocomplete="off"를 autocomplete="new-password"로 바꾸면 됩니다.
언급URL : https://stackoverflow.com/questions/21168367/angularjs-chrome-autocomplete-dilemma
'source' 카테고리의 다른 글
| 이 단순한 문자열은 유효한 JSON으로 간주됩니까? (0) | 2023.02.12 |
|---|---|
| REST 템플릿 교환을 모의하려면 어떻게 해야 하나요? (0) | 2023.02.12 |
| react-router v4에서 history.push/Link/Redirect를 포함한 파라미터를 전달하려면 어떻게 해야 합니까? (0) | 2023.02.12 |
| C#을 Oracle 데이터베이스에 연결하기 위해 필요한 최소 클라이언트 설치 공간은 얼마입니까? (0) | 2023.02.12 |
| @RestController vs @RepositoryRestResource를 사용하는 경우 (0) | 2023.02.12 |