2014-12-21 4 views
2

내 창을 닫을 때 로그 오프해야한다는 것을 내 사용자에게 알리는 방법을 찾고 있습니다. 나는 이미이 코드를 발견했습니다 : 내 페이지를 닫을 때창을 닫을 때 경고 상자가 나타나지만 다시로드 할 때 없음

window.onbeforeunload = confirmExit; 
function confirmExit() 
{ 
    return "It is better if you log out, before you close this page!"; 
} 
$(function() 
{ 
    $("a").click(function() 
    { 
     window.onbeforeunload = null; 
    }); 
}); 

이 완벽하게 작동합니다. 내가 원하는대로,하지만 그것은 또한 페이지를 다시로드 할 때 표시됩니다.

누구나이 문제를 해결하는 방법에 대해 생각해 볼 수 있습니다.

+0

아니요. 페이지를 새로 고침 할 때'onbeforeunload'가 실행됩니다. 그러나 독자적인 청취자에게'F5'를 바인드 해, 페이지를 리프레시 합니다만, 경고 (?)를 무효로 할 수 있습니다. – Jonathan

+0

동일합니다 : http://stackoverflow.com/questions/2584124/javascript-register-window-tab-closing-event-before-window-tab-close하지만 페이지 재로드 문제는 논의하지 않았습니다. –

+0

'onbeforeunload' 전에 ​​트리거되는 onkeydown 이벤트에 바인딩 할 수 있습니다. 그러나 마우스로 페이지를 새로 고침하지 마십시오. – sergolius

답변

1

저는 이것이 귀하의 문제를 해결하는 데 도움이 될 것이라고 믿습니다. 이것은 키 코드 (116)가 사용자에 의해 눌려 졌는지 (f5 키) 또는 다시 말해서 리프레시 버튼을 먼저 검출함으로써 작동한다. 이벤트가 beforeunload가 프롬프트를 표시하지 않도록이 버튼 누름의 상태를 저장합니다. 다음은 필요한 자바 스크립트/jquery입니다.

참고 : 참고 :이 예제는 jsfiddle에서 예상대로 작동하지 않으므로 예제를 제외 시켰습니다.

//set the variable exit to true initially because you haven't hit 
//the f5 button yet to refresh 
var exit = true; 

//on keydown event to check if the f5 or 116 keycode has been pressed 
$(window).on("keydown",function(e){//begin window on keydown event 

    //if the keycode = 116 
    //in other words the user has pressed the f5 key 
    if(e.which === 116){//begin if then 

     //set exit to false because so the prompt doesn't display 
     exit = false; 

    }//end if then 


});//end window on keydown event 


    //bind the beforeunload event to the window 
    $(window).bind("beforeunload", function() {//begin event 

     //if exit = true then display the prompt 
     if (exit === true) {//begin if then 

      //display the prompt 
      //note the browser may over ride the string in your return value 
      return "Are you sure you want to leave?"; 
     } else { 

      //do nothing, no prompt will be created 
      return; 

     }//end if then 


});//end event 
+0

완벽하게 작동하여 'F5'버튼을 잡을 수 있지만 브라우저의 해당 버튼을 누르면 전체 답변이 아닌, 가능하지는 않습니다. – Rings

+0

나는 그 일을하는 방법에 대해 하나 더 생각했다. 작동하는지 알려주지. –

+0

솔루션에서 PHP를 사용할 수 있는지 궁금합니다. –

관련 문제