programing

브라우저 창 닫기 이벤트를 캡처하는 방법은 무엇입니까?

javamemo 2023. 7. 24. 22:09
반응형

브라우저 창 닫기 이벤트를 캡처하는 방법은 무엇입니까?

브라우저 창/탭 닫기 이벤트를 캡처하려고 합니다.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");
    ...
});
window.onbeforeunload = function () {
    return "Do you really want to close?";
};

크로스 브라우저 솔루션(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 의 참고 사항을 참조하십시오.

제 대답은 간단한 벤치마크를 제공하는 것입니다.

방법

@SLAK 답변을 참조하십시오.

$(window).on("beforeunload", function() { 
    return inFormOrLink ? "Do you really want to close?" : null; 
})

브라우저가 페이지를 종료하는 데 얼마나 걸립니까?

사용자가 페이지(x버튼 또는 +)를 닫을 때마다 브라우저는 지정된 페이지를 실행합니다.beforeunload코드, 하지만 무기한은 아닙니다.return 'Do you really want to close?사용자가 응답할 때까지 대기합니다.

크롬: 2초.
Firefox: ∞(또는 두 번 클릭하거나 강제 종료)
가장자리: ∞(또는 더블 클릭)
탐험가 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.

다양한 이유로 앵커 태그를 사용하는 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를 사용했지만, on before unload 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;
})

OnSubmit을 처리하고 나중에 OnBeforeUnload 처리기에서 확인할 플래그를 설정할 수 있습니다.

불행히도 이벤트가 다시 로드, 새 페이지 리디렉션 또는 브라우저 닫기인지 여부에 관계없이 트리거됩니다.다른 방법은 이벤트를 트리거하는 ID를 포착하는 것입니다. 폼이면 아무 기능도 트리거하지 마십시오. 폼의 ID가 아니면 페이지가 닫힐 때 원하는 작업을 수행하십시오.그것도 직접적으로 가능하고 지루한지 잘 모르겠습니다.

고객이 탭을 닫기 전에 몇 가지 작은 작업을 할 수 있습니다. javascript 탐지 브라우저 닫기/브라우저 닫기/브라우저 닫기 전에 작업 목록이 커서 탭이 닫히면 속수무책입니다.당신은 그것을 시도할 수 있지만, 제 경험으로는 그것에 의존하지 마세요.

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";
  /* Do you small action code here */
  (e || window.event).returnValue = confirmationMessage; //Gecko + IE
  return confirmationMessage;                            //Webkit, Safari, Chrome
});

https://developer.mozilla.org/en-US/docs/Web/Reference/Events/beforeunload?redirectlocale=en-US&redirectslug=DOM/Mozilla_event_reference/beforeunload

jQuery(window).bind("beforeunload", function (e) {
    var activeElementTagName = e.target.activeElement.tagName;
    if (activeElementTagName != "A" && activeElementTagName != "INPUT") {
        return "Do you really want to close?";
    }
})

양식 제출로 인해 다른 페이지로 이동하는 경우(내가 생각하는 것처럼), 따라서 트리거링:beforeunload), 양식 제출을 Ajax 호출로 변경할 수 있습니다.이렇게 하면, 그들이 양식을 제출할 때 당신의 페이지를 떠나지 않을 것이고 당신은 당신의 페이지를 사용할 수 있습니다.beforeunload원하는 대로 바인딩 코드.

jQuery 1.7에서 .live() 메서드는 더 이상 사용되지 않습니다..on()을 사용하여 이벤트 핸들러를 연결합니다.이전 버전의 jQuery 사용자는 .live()보다 .delegate()를 사용해야 합니다.

$(window).bind("beforeunload", function() {
    return true || confirm("Do you really want to close?"); 
}); 

완전 또는 연계로

$(window).unbind();

내 문제:'on before unload' 이벤트는 홀수의 제출(클릭)이 있는 경우에만 트리거됩니다.저는 제 솔루션을 작동시키기 위해 SO의 유사한 스레드의 솔루션을 조합했습니다. 제 코드는 말할 수 있을 것입니다.

<!--The definition of event and initializing the trigger flag--->


$(document).ready(function() {
  updatefgallowPrompt(true);
  window.onbeforeunload = WarnUser; 
}

function WarnUser() {
  var allowPrompt = getfgallowPrompt();
  if(allowPrompt) {
    saveIndexedDataAlert();
    return null;
  } else {
    updatefgallowPrompt(true);
    event.stopPropagation
  }
}

<!--The method responsible for deciding weather the unload event is triggered from submit or not--->
function saveIndexedDataAlert() {
  var allowPrompt = getfgallowPrompt();
  var lenIndexedDocs = parseInt($('#sortable3 > li').size()) + parseInt($('#sortable3 > ul').size());

  if(allowPrompt && $.trim(lenIndexedDocs) > 0) {
    event.returnValue = "Your message";
  } else {
    event.returnValue = "   ";
    updatefgallowPrompt(true);
  }
}

<!---Function responsible to reset the trigger flag---->
$(document).click(function(event) {  
  $('a').live('click', function() { updatefgallowPrompt(false); });
});

<!--getter and setter for the flag---->
function updatefgallowPrompt (allowPrompt){ //exit msg dfds
  $('body').data('allowPrompt', allowPrompt);   
}   

function getfgallowPrompt(){        
  return $('body').data('allowPrompt'); 
}

확인만...

function wopen_close(){
  var w = window.open($url, '_blank', 'width=600, height=400, scrollbars=no, status=no, resizable=no, screenx=0, screeny=0');
  w.onunload = function(){
    if (window.closed) {
       alert("window closed");
    }else{ 
       alert("just refreshed");
    }
  }
}

이것도 사용해 보세요.

window.onbeforeunload = function ()
{       
    if (pasteEditorChange) {
        var btn = confirm('Do You Want to Save the Changess?');
           if(btn === true ){
               SavetoEdit();//your function call
           }
           else{
                windowClose();//your function call
           }
    }  else { 
        windowClose();//your function call
    }
};
var validNavigation = false;
            jQuery(document).ready(function () {

                wireUpEvents();
            });

            function endSession() {
                // Browser or broswer tab is closed
                // Do sth here ...
                alert("bye");
            }

            function wireUpEvents() {
                /*
                * For a list of events that triggers onbeforeunload on IE
                * check http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
                */
                window.onbeforeunload = function () {
                    debugger
                    if (!validNavigation) {
                        endSession();
                    }
                }

                // Attach the event keypress to exclude the F5 refresh
                $(document).bind('keypress', function (e) {
                    debugger
                    if (e.keyCode == 116) {
                        validNavigation = true;
                    }
                });

                // Attach the event click for all links in the page
                $("a").bind("click", function () {
                    debugger
                    validNavigation = true;
                });

                // Attach the event submit for all forms in the page
                $("form").bind("submit", function () {
                    debugger
                    validNavigation = true;
                });

                // Attach the event click for all inputs in the page
                $("input[type=submit]").bind("click", function () {
                    debugger
                    validNavigation = true;
                });

            }`enter code here`

다음은 나에게 효과가 있었습니다.

 $(window).unload(function(event) {
    if(event.clientY < 0) {
        //do whatever you want when closing the window..
    }
 });

언급URL : https://stackoverflow.com/questions/1631959/how-to-capture-the-browser-window-close-event

반응형