Programming

페이지를 떠나기 전에 JavaScript

procodes 2020. 5. 5. 20:51
반응형

페이지를 떠나기 전에 JavaScript


사용자가 페이지를 떠나기 전에 확인하고 싶습니다. 그가 ok라고 말하면 새 페이지로 리디렉션되거나 취소됩니다. onunload로 만들려고했습니다.

<script type="text/javascript">
function con() {
    var answer = confirm("do you want to check our other products")
    if (answer){

        alert("bye");
    }
    else{
        window.location = "http://www.example.com";
    }
}
</script>
</head>

<body onunload="con();">
<h1 style="text-align:center">main page</h1>
</body>
</html>

그러나 페이지가 이미 닫힌 후에 확인됩니까? 제대로하는 방법?

누군가가 jQuery로 어떻게하는지 보여 주면 더 좋을까요?


onunload(또는 onbeforeunload)은 사용자를 다른 페이지로 리디렉션 할 수 없습니다. 이것은 보안상의 이유입니다.

사용자가 페이지를 떠나기 전에 프롬프트를 표시하려면 onbeforeunload다음을 사용하십시오 .

window.onbeforeunload = function(){
  return 'Are you sure you want to leave?';
};

또는 jQuery를 사용하여 :

$(window).bind('beforeunload', function(){
  return 'Are you sure you want to leave?';
});

이것은 사용자에게 페이지를 남기고 싶은지를 묻고 페이지에 머 무르도록 선택하면 리디렉션 할 수 없습니다. 그들이 떠나기로 선택하면, 브라우저는 그들이 지시 한 곳으로 이동합니다.

onunload페이지를 언로드하기 전에 작업을 수행 하는 사용할 수 있지만 페이지에서 리디렉션 할 수는 없습니다 (Chrome 14+는 내부에서 알림 차단 onunload).

window.onunload = function() {
    alert('Bye.');
}

또는 jQuery를 사용하여 :

$(window).unload(function(){
  alert('Bye.');
});

이 코드는 양식 상태가 변경되었는지 감지 할 때도 발생합니다.

$('#form').data('serialize',$('#form').serialize()); // On load save form current state

$(window).bind('beforeunload', function(e){
    if($('#form').serialize()!=$('#form').data('serialize'))return true;
    else e=null; // i.e; if form state change show warning box, else don't show it.
});

Google JQuery 양식 직렬화 기능을 사용하면 모든 양식 입력을 수집하여 배열에 저장합니다. 나는이 설명이 충분하다고 생각합니다 :)


현재 페이지를 떠날 때 경고합니다

<script type='text/javascript'>
function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye; 

</script>

Chrome 14 이상에서 팝업을 표시하려면 다음을 수행해야합니다.

jQuery(window).bind('beforeunload', function(){
    return 'my text';
});

사용자는 체류 또는 휴가를 원하는지 묻습니다.


저장하지 않은 데이터가있을 때 확인 메시지를 표시하기 위해 수행 한 작업

window.onbeforeunload = function () {
            if (isDirty) {
                return "There are unsaved data.";
            }
            return undefined;
        }

"undefined"를 반환하면 확인이 비활성화됩니다.

참고 : "null"을 반환하면 IE에서 작동하지 않습니다.

또한 "정의되지 않음"을 사용하여 확인을 비활성화 할 수 있습니다.

window.onbeforeunload = undefined;

You can use the following one-liner to always ask the user before leaving the page.

window.onbeforeunload = s => "";

To ask the user when something on the page has been modified, see this answer.


<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">

<p>Close this window, press F5 or click on the link below to invoke the onbeforeunload event.</p>

<a href="https://www.w3schools.com">Click here to go to w3schools.com</a>

<script>
function myFunction() {
    return "Write something clever here...";
}
</script>

</body>
</html>

https://www.w3schools.com/tags/ev_onbeforeunload.asp


Just a bit more helpful, enable and disable

$(window).on('beforeunload.myPluginName', false); // or use function() instead of false
$(window).off('beforeunload.myPluginName');

Normally you want to show this message, when the user has made changes in a form, but they are not saved.

Take this approach to show a message, only when the user has changed something

var form = $('#your-form'),
  original = form.serialize()

form.submit(function(){
  window.onbeforeunload = null
})

window.onbeforeunload = function(){
  if (form.serialize() != original)
    return 'Are you sure you want to leave?'
}

참고URL : https://stackoverflow.com/questions/7080269/javascript-before-leaving-the-page

반응형