페이지를 닫을 때 (떠나지 않을 때) jquery beforeunload?
"페이지에서 나가시겠습니까?"를 어떻게 표시 할 수 있습니까? 사용자가 실제로 페이지를 닫으려고 할 때 (브라우저 창이나 탭에서 X 버튼 클릭) 페이지를 벗어나려고 할 때 (다른 링크 클릭).
내 고객은 사용자가 페이지를 닫으려고 할 때 "페이지에서 나가시겠습니까? 아직 장바구니에 항목이 있습니다."라는 메시지가 표시되기를 원합니다.
불행히도 $(window).bind('beforeunload')
사용자가 페이지를 닫을 때만 실행되지는 않습니다.
jQuery :
function checkCart() {
$.ajax({
url : 'index.php?route=module/cart/check',
type : 'POST',
dataType : 'json',
success : function (result) {
if (result) {
$(window).bind('beforeunload', function(){
return 'leave?';
});
}
}
})
}
JQuery 를 사용하여이를 수행 할 수 있습니다 .
예를 들어 ,
<a href="your URL" id="navigate"> click here </a>
당신의 JQuery
의지는,
$(document).ready(function(){
$('a').on('mousedown', stopNavigate);
$('a').on('mouseleave', function () {
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
});
});
function stopNavigate(){
$(window).off('beforeunload');
}
그리고 얻을 남기기 메시지 알림이 될 것입니다,
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
$(window).on('unload', function(){
logout();
});
이 솔루션은 모든 브라우저에서 작동하며 테스트했습니다.
Ajax에 자바 스크립트 사용해보기
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
참조 링크
예 2 :
document.getElementsByClassName('eStore_buy_now_button')[0].onclick = function(){
window.btn_clicked = true;
};
window.onbeforeunload = function(){
if(!window.btn_clicked){
return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
}
};
여기에서 사용자가 버튼을 클릭 할 때까지 페이지를 떠날 때마다 사용자에게 경고합니다.
데모 : http://jsfiddle.net/DerekL/GSWbB/show/
크레딧은 여기로 가야합니다 : window.onbeforeunload가 트리거 될 때 링크가 클릭되었는지 감지하는 방법?
기본적으로 솔루션은 링크 또는 창으로 인해 언로드 이벤트가 발생했는지 감지하는 리스너를 추가합니다.
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function(e) {
if(link_was_clicked) {
return;
}
return confirm('Are you sure?');
}
https://stackoverflow.com/a/1632004/330867에 표시된 대로이 페이지의 이탈을 시작하는 항목을 "필터링"하여 구현할 수 있습니다.
주석에서 언급했듯이 다른 질문에있는 코드 의 새 버전 은 다음 과 같습니다. 여기 에는 질문에서 만든 ajax 요청도 포함됩니다.
var canExit = true;
// For every function that will call an ajax query, you need to set the var "canExit" to false, then set it to false once the ajax is finished.
function checkCart() {
canExit = false;
$.ajax({
url : 'index.php?route=module/cart/check',
type : 'POST',
dataType : 'json',
success : function (result) {
if (result) {
canExit = true;
}
}
})
}
$(document).on('click', 'a', function() {canExit = true;}); // can exit if it's a link
$(window).on('beforeunload', function() {
if (canExit) return null; // null will allow exit without a question
// Else, just return the message you want to display
return "Do you really want to close?";
});
Important: You shouldn't have a global variable defined (here canExit
), this is here for simpler version.
Note that you can't override completely the confirm message (at least in chrome). The message you return will only be prepended to the one given by Chrome. Here's the reason : How can I override the OnBeforeUnload dialog and replace it with my own?
Try this, loading data via ajax
and displaying through return statement.
<script type="text/javascript">
function closeWindow(){
var Data = $.ajax({
type : "POST",
url : "file.txt", //loading a simple text file for sample.
cache : false,
global : false,
async : false,
success : function(data) {
return data;
}
}).responseText;
return "Are you sure you want to leave the page? You still have "+Data+" items in your shopping cart";
}
window.onbeforeunload = closeWindow;
</script>
jQuery Solution:
With 'beforeunload'
event attached, when you close the page, hits the back button or reload the page, a confirmation box will prompt to ask you whether you really want to go, choose ok to exit the page: cancel to stop the page from exit and stay on the same page.
In addition, you are allow to add your own message inside the confirmation box :
$(window).bind('beforeunload', function(){
return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
});
P.S: The 'beforeunload'
event is supported since jQuery 1.4.
Javascript:
For IE and FF < 4, set window.event.returnValue
to the string you wish to display, and then return it for Safari (use null
instead to allow normal behavior):
window.onbeforeunload = function (e) {
var e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Any string';
}
// For Safari
return 'Any string';
};
You can try 'onbeforeunload
' event.
Also take a look at this-
Dialog box runs for 1 sec and disappears?
참고URL : https://stackoverflow.com/questions/18783535/jquery-beforeunload-when-closing-not-leaving-the-page
'program story' 카테고리의 다른 글
C ++ 컴파일 버그? (0) | 2020.10.21 |
---|---|
문자열 + i를 연결하는 방법? (0) | 2020.10.21 |
jQuery Button.click () 이벤트가 두 번 트리거됩니다. (0) | 2020.10.20 |
C #에서 인라인 함수를 만드는 방법 (0) | 2020.10.20 |
간단한 PHP 개발 서버가 있습니까? (0) | 2020.10.20 |