search

Home  >  Q&A  >  body text

How to capture user's response when using window.onbeforeunload

<p>Is there a way to capture whether the user clicked "OK" or "Cancel"? </p> <p>I need to do something only when the user leaves the page....</p>
P粉245003607P粉245003607485 days ago473

reply all(1)I'll reply

  • P粉914731066

    P粉9147310662023-08-15 09:11:48

    This is the solution I use in situations where I need to perform some action (such as clearing the session) when the user navigates from the page.

    I have 2 global variables

    var clearSession = true;
    var confirmExit = true;
    
    
        window.onbeforeunload = function() { return confirmExit(); }
        window.onunload = function() { return clearSession(); }
    
    function confirmExit() {
        if (needToConfirm == true) {       
    
            return "退出页面?";
        }
    }
    
    
    function clearSession() {
    
         if (clearSession == true) {
            alert("在服务器上终止会话!!!");
            PageMethods.ClearSession();
        }
    }

    Then when each page submits/button/dropdown etc you need to make sure the above global variable is set to false.

    Hope it helps someone.

    reply
    0
  • Cancelreply