How to capture browser close event?

后端 未结 4 1177
隐瞒了意图╮
隐瞒了意图╮ 2020-11-29 10:18

I want to capture the browser close event in my application and show a confirm box to user. I am using JSF 2.0 and richfaces 4.0.

相关标签:
4条回答
  • 2020-11-29 10:45

    Use the beforeunload event.

    window.onbeforeunload = function(event) {
    
        event = event || window.event;
    
        var confirmClose = 'Are you sure?';
    
        // For IE and Firefox prior to version 4
        if (event) {
           event.returnValue = confirmClose;
        }
    
        // For Safari
        return confirmClose;
    
    }
    

    Keep in mind this will be fire for other events besides closing the window, such as reloading and form submission.

    0 讨论(0)
  • 2020-11-29 10:46

    onbeforeunload

    < body onbeforeunload="alert('Closing');">
    

    Example :

    <html> 
    <head>
    <title>`onbeforeunload` Event Demo</title>
    </head>
    <body onbeforeunload="return 'Are you sure you want to exit ?';">
    </body> 
    </html> 
    
    0 讨论(0)
  • 2020-11-29 10:46

    Attach a handler to the unload event.

    0 讨论(0)
  • 2020-11-29 10:48
    window.onbeforeunload = function () 
    {
      var shallIAlertUser = Do_Whatever(); //get boolen value
      if (shallIAlertUser) {
        //this will alert user
        return 'Are you sure?';
      }
      else {
        //this wont
        window.onbeforeunload = undefined;
      }
    };
    
    0 讨论(0)
提交回复
热议问题