브라우저 창 / 탭 닫기 이벤트를 캡처하고 싶습니다. jQuery로 다음을 시도했습니다.
jQuery(window).bind(
"beforeunload",
function() {
return confirm("Do you really want to close?")
}
)
그러나 양식 제출에서도 작동하지만 이는 내가 원하는 것이 아닙니다. 사용자가 창을 닫을 때만 트리거되는 이벤트를 원합니다.
답변
그만큼 beforeunload
사용자가 어떤 이유로 페이지를 단풍 때마다 이벤트가 발생합니다.
예를 들어, 사용자가 양식을 제출하거나, 링크를 클릭하거나, 창 또는 탭을 닫거나, 주소 표시 줄, 검색 상자 또는 책갈피를 사용하여 새 페이지로 이동하면 시작됩니다.
다음 코드를 사용하여 양식 제출 및 하이퍼 링크 (다른 프레임 제외)를 제외 할 수 있습니다.
var inFormOrLink;
$('a').on('click', function() { inFormOrLink = true; });
$('form').on('submit', function() { inFormOrLink = true; });
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
1.7보다 오래된 jQuery 버전의 경우 다음을 시도하십시오.
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
이 live
메소드는 submit
이벤트 와 함께 작동하지 않으므로 새 양식을 추가하는 경우 핸들러도 해당 오브젝트에 바인드해야합니다.
다른 이벤트 핸들러가 제출 또는 탐색을 취소하면 나중에 실제로 창이 닫히면 확인 메시지가 표시되지 않습니다. submit
및 click
이벤트 의 시간을 기록하고 beforeunload
몇 초 후에 발생 하는지 확인 하여 문제를 해결할 수 있습니다.
답변
어쩌면 beforeunload
폼의 submit
이벤트 핸들러 내 에서 이벤트 핸들러를 바인딩 해제 할 수 있습니다 .
jQuery('form').submit(function() {
jQuery(window).unbind("beforeunload");
...
});
답변
크로스 브라우저 솔루션 (Chrome 21, IE9, FF15에서 테스트)의 경우 약간 수정 된 Slaks 코드 버전 인 다음 코드를 사용하는 것이 좋습니다.
var inFormOrLink;
$('a').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
Firefox 4부터 “정말로 닫으시겠습니까?”라는 메시지가 표시됩니다. 가 표시되지 않습니다. FF는 일반 메시지 만 표시합니다. https://developer.mozilla.org/en-US/docs/DOM/window.onbeforeunload 에서 참고 사항 참조
답변
window.onbeforeunload = function () {
return "Do you really want to close?";
};
답변
여러 가지 이유로 Anchor 태그를 사용하는 Telerik (예 : RadComboBox) 및 DevExpress와 같은 타사 컨트롤과 잘 작동하는 솔루션의 경우 다음 코드를 사용하는 것이 좋습니다. 앵커 태그 타겟팅 :
var inFormOrLink;
$('a[href]:not([target]), a[href][target=_self]').live('click', function() { inFormOrLink = true; });
$('form').bind('submit', function() { inFormOrLink = true; });
$(window).bind('beforeunload', function(eventObject) {
var returnValue = undefined;
if (! inFormOrLink) {
returnValue = "Do you really want to close?";
}
eventObject.returnValue = returnValue;
return returnValue;
});
답변
내 대답은 간단한 벤치 마크를 제공하는 것입니다.
어떻게
@SLaks answer를 참조하십시오 .
$(window).on("beforeunload", function() {
return inFormOrLink ? "Do you really want to close?" : null;
})
브라우저가 페이지를 종료하는 데 얼마나 걸립니까?
사용자가 페이지를 닫을 때마다 ( x버튼 또는 CTRL+ W) 브라우저는 주어진 beforeunload
코드를 실행 하지만 무한정 실행 되지는 않습니다. 유일한 예외는 확인 상자 (return 'Do you really want to close?
, 사용자의 응답을 기다릴 ) .
크롬 : 2 초
Firefox : ∞ (또는 더블 클릭 또는 강제 종료)
Edge : ∞ (또는 더블 클릭)
Explorer 11 : 0 초.
사파리 : TODO
우리가 이것을 테스트하기 위해 사용한 것 :
- 요청 로그가있는 Node.js Express 서버
- 다음 짧은 HTML 파일
브라우저가 페이지를 (동기식으로) 종료하기 전에 가능한 많은 요청을 보내는 것입니다.
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function request() {
return $.ajax({
type: "GET",
url: "http://localhost:3030/" + Date.now(),
async: true
}).responseText;
}
window.onbeforeunload = () => {
while (true) {
request();
}
return null;
}
</script>
</body>
</html>
크롬 출력 :
GET /1480451321041 404 0.389 ms - 32
GET /1480451321052 404 0.219 ms - 32
...
GET /hello/1480451322998 404 0.328 ms - 32
1957ms ≈ 2 seconds // we assume it's 2 seconds since requests can take few milliseconds to be sent.
답변
Slaks 답변을 사용했지만 onbeforeunload returnValue가 문자열로 구문 분석 된 다음 브라우저의 확인 상자에 표시되므로 그대로 작동하지 않았습니다. 따라서 “true”와 같이 true 값이 표시되었습니다.
그냥 반품을 사용했습니다. 여기 내 코드가 있습니다
var preventUnloadPrompt;
var messageBeforeUnload = "my message here - Are you sure you want to leave this page?";
//var redirectAfterPrompt = "http://www.google.co.in";
$('a').live('click', function() { preventUnloadPrompt = true; });
$('form').live('submit', function() { preventUnloadPrompt = true; });
$(window).bind("beforeunload", function(e) {
var rval;
if(preventUnloadPrompt) {
return;
} else {
//location.replace(redirectAfterPrompt);
return messageBeforeUnload;
}
return rval;
})
