0
$(window).on("beforeunload", function(){
    window.open("survey.html");
    return "Are you sure you want to leave?";
});

Once user try to exit from the web page this will ask "Are you sure you want to leave?"

Is there a way to know whether the user click yes or not from this popup ?

Eshan Sudharaka
  • 607
  • 2
  • 9
  • 16

2 Answers2

0

Simply use window.confirm():

$(window).on("beforeunload", function(){
    if (window.confirm("Are you sure you want to leave?") {
        window.open("survey.html");
    }
});
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
0

Let us see how to achieve this using JavaScript. In JavaScript we have events such as onbeforeunload and onunload. These events as their name suggest, gets triggered whenever the page gets unload. This happens if user close the browser or move to different page. We can use these events to call any javascript handler function. Register for an event from body tag.

<script language="javascript">
function fnUnloadHandler() {
       // Add your code here
       alert("Unload event.. Do something to invalidate users session..");
}
</script>
<body onbeforeunload="fnUnloadHandler()">
    <!-- Your page content -->
</body>

Here in above code snippet we have registered the event onbeforeunload from tag. You can also registered for the event using window.eventname handler. For e.g.

window.onbeforeunload = function() {
       // Add your code here
       alert("Unload event.. Do something to invalidate users session..");
}
Sajith
  • 856
  • 4
  • 19
  • 48