복붙노트

[JQUERY] 브라우저 가까운 이벤트를 감지하는 시도

JQUERY

브라우저 가까운 이벤트를 감지하는 시도

해결법


  1. 1.이 코드를 시도?

    이 코드를 시도?

    window.onbeforeunload = function (event) {
        var message = 'Important: Please click on \'Save\' button to leave this page.';
        if (typeof event == 'undefined') {
            event = window.event;
        }
        if (event) {
            event.returnValue = message;
        }
        return message;
    };
    
    $(function () {
        $("a").not('#lnkLogOut').click(function () {
            window.onbeforeunload = null;
        });
        $(".btn").click(function () {
            window.onbeforeunload = null;
    });
    });
    

    두 번째 기능은 #lnkLogOut 및 .btn 요소를 클릭하는 동안 묻지 않도록 선택 사항입니다.

    한 가지 더, (심지어 또한 최신 버전) 파이어 폭스에서 작동하지 않습니다 프롬프트 사용자 정의. 그것에 대해 자세한 내용은이 스레드로 이동하십시오.


  2. 2.다양한 기사를 참조하고 시행 착오 테스트를하고, 마지막으로 나를 위해 완벽하게 작동이 아이디어를 개발했다.

    다양한 기사를 참조하고 시행 착오 테스트를하고, 마지막으로 나를 위해 완벽하게 작동이 아이디어를 개발했다.

    아이디어는 브라우저를 닫아 트리거 언로드 이벤트를 감지하는 것이 었습니다. 이 경우, 마우스가 닫기 버튼 ( 'X')에서 지적, 창 밖으로 될 것입니다.

    $(window).on('mouseover', (function () {
        window.onbeforeunload = null;
    }));
    $(window).on('mouseout', (function () {
        window.onbeforeunload = ConfirmLeave;
    }));
    function ConfirmLeave() {
        return "";
    }
    var prevKey="";
    $(document).keydown(function (e) {            
        if (e.key=="F5") {
            window.onbeforeunload = ConfirmLeave;
        }
        else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {                
            window.onbeforeunload = ConfirmLeave;   
        }
        else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
            window.onbeforeunload = ConfirmLeave;
        }
        else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
            window.onbeforeunload = ConfirmLeave;
        }
        prevKey = e.key.toUpperCase();
    });
    

    ConfirmLeave 기능은 경우에 텍스트를 다음 메시지를 사용자 정의 반환 할 필요 기능 ConfirmLeave에서 빈 문자열 대신 표시 할 수는 ()가, 위쪽 팝업 기본 메시지를 줄 것이다.


  3. 3.리눅스 크롬 환경에서 나를 위해 코드 작품을 다음보십시오. 확인 jQuery를 실행하기 전에 문서에 첨부되어 있습니다.

    리눅스 크롬 환경에서 나를 위해 코드 작품을 다음보십시오. 확인 jQuery를 실행하기 전에 문서에 첨부되어 있습니다.

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

    간단한 추적의 다음 단계의 경우 :

    그것은 다음과 같은 그림을 표시해야합니다 :


  4. 4.안녕 난 단지 새로운 브라우저에서 작동하는 복잡한 솔루션을 가지고 :

    안녕 난 단지 새로운 브라우저에서 작동하는 복잡한 솔루션을 가지고 :

    단지 사용자가 창을 닫을 때으로 onClose 이벤트가 시작됩니다, 서버에 웹 소켓을 엽니 다


  5. 5.다음 스크립트는 크롬과 IE에 메시지를 줄 것이다 :

    다음 스크립트는 크롬과 IE에 메시지를 줄 것이다 :

    <script>
    window.onbeforeunload = function (e) {
    // Your logic to prepare for 'Stay on this Page' goes here 
    
        return "Please click 'Stay on this Page' and we will give you candy";
    };
    </script>
    

    크롬

    IE

    파이어 폭스에서 당신은 일반적인 메시지가 표시됩니다

    메커니즘은 지연에는 서버 호출이 작동하지 않게 동기, 당신은 여전히 ​​모달 사용자가 페이지에서 유지하기로 결정하면 표시되는 창,하지만 떠나는 그를 방지 할 수있는 방법 같은 메커니즘을 준비 할 수 있습니다.

    코멘트에서 질문에 대한 응답

    F5는 너무 + F4를 Alt 키 것, 다시 이벤트가 발생합니다.


  6. 6.피닉스 말했듯이, 사용 jQuery를 .bind 방법,하지만 더 브라우저 호환성을 위해 당신은 문자열을 반환해야합니다

    피닉스 말했듯이, 사용 jQuery를 .bind 방법,하지만 더 브라우저 호환성을 위해 당신은 문자열을 반환해야합니다

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

    developer.mozilla.org 자세한 세부 사항에서 확인하실 수 있습니다


  7. 7.jQuery를 .bind ()는 더 이상 사용되지 않습니다. 대신) (CSTE 연구진 사용

    jQuery를 .bind ()는 더 이상 사용되지 않습니다. 대신) (CSTE 연구진 사용

    $(window).on("beforeunload", function() {
        runBeforeClose();
    });
    

  8. 8.아마 경로 탐지 마우스를 사용하는 것이 좋습니다.

    아마 경로 탐지 마우스를 사용하는 것이 좋습니다.

    BrowserClosureNotice에서 당신은 그것을 할 수있는 데모 예를 순수 자바 스크립트 라이브러리를 가지고있다.

    그것은 완벽하지만, 문서 또는 마우스 이벤트의 문제를 방지하지 않습니다 ...


  9. 9.

    <script type="text/javascript">
    window.addEventListener("beforeunload", function (e) {
    
      var confirmationMessage = "Are you sure you want to leave this page without placing the order ?";
      (e || window.event).returnValue = confirmationMessage;
      return confirmationMessage;
    
    });
    </script>
    

    이 코드를하려고이 나를 위해 잘 작동됩니다하시기 바랍니다. 이 사용자 정의 메시지는 크롬 브라우저에오고 있지만, 모질라에이 메시지가 표시되지 않습니다.


  10. 10.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    
    <script type="text/javascript" language="javascript">
    
    var validNavigation = false;
    
    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() {
      if (!validNavigation) {
    
                var ref="load";
          $.ajax({
                type: 'get',
                async: false,
                url: 'logout.php',
     data:
                {
                    ref:ref               
                },
                 success:function(data)
                {
                    console.log(data);
                }
                });
         endSession();
      }
     }
    
    // Attach the event keypress to exclude the F5 refresh
    $(document).bind('keypress', function(e) {
    if (e.keyCode == 116){
      validNavigation = true;
    }
    });
    
    // Attach the event click for all links in the page
    $("a").bind("click", function() {
    validNavigation = true;
    });
    
     // Attach the event submit for all forms in the page
     $("form").bind("submit", function() {
     validNavigation = true;
     });
    
     // Attach the event click for all inputs in the page
     $("input[type=submit]").bind("click", function() {
     validNavigation = true;
     });
    
    }
    
    // Wire up the events as soon as the DOM tree is ready
    $(document).ready(function() {
    wireUpEvents();  
    }); 
    </script> 
    

    이 가까이 한 사용자는 자동으로 사용자 계정을 로그 아웃 할 브라우저 또는 브라우저 탭을 기록 할 때 사용됩니다 ...


  11. 11.당신이 뭔가를 시도 할 수 있습니다.

    당신이 뭔가를 시도 할 수 있습니다.

    <html>
    <head>
        <title>test</title>
        <script>
            function openChecking(){
                // alert("open");
                var width = Number(screen.width-(screen.width*0.25));  
                var height = Number(screen.height-(screen.height*0.25));
                var leftscr = Number((screen.width/2)-(width/2)); // center the window
                var topscr = Number((screen.height/2)-(height/2));
                var url = "";
                var title = 'popup';
                var properties = 'width='+width+', height='+height+', top='+topscr+', left='+leftscr;
                var popup = window.open(url, title, properties);
                var crono = window.setInterval(function() {
                    if (popup.closed !== false) { // !== opera compatibility reasons
                        window.clearInterval(crono);
                        checkClosed();
                    }
                }, 250); //we check if the window is closed every 1/4 second
            }   
            function checkClosed(){
                alert("closed!!");
                // do something
            }
        </script>    
    </head>
    <body>
        <button onclick="openChecking()">Click Me</button>
    </body>
    </html>
    

    사용자가 창을 닫을 때, 콜백 해고 될 것이다.

  12. from https://stackoverflow.com/questions/20853142/trying-to-detect-browser-close-event by cc-by-sa and MIT license