0

I want to show popup only when user close the browser window. But, In the following code. It showing popup when I refresh the page.

My Code

<script type="text/javascript">
    $(document).ready(function()
    {
        var key = true;
        $(window).bind('beforeunload', function(e){
            if(key)
             return confirm("Do you really want to close? This will log you out of your profile."); 
         e.preventDefault()
        }); 
        $(document).on("click","a",function() {
          key=false; 
        });    
    });
</script>
user3909863
  • 391
  • 2
  • 5
  • 12

2 Answers2

1

This is essentially what you need.

Source: open a custom popup on browser window/tab close

JSFiddle: http://jsfiddle.net/SQAmG/5/

var popit = true;
window.onbeforeunload = function() { 
     if(popit == true) {
          popit = false;
          return "Are you sure you want to leave?"; 
     }
}

EDIT

Use HTML5 Web Storage to simulate sessions within the browser. Here you would want to use sessionStorage rather than localStorage so the session ends when the browser window is completely closed.

If the sessionStorage variable is set, do not start the popup, otherwise allow the popup code to execute.

HTML5 Web Storage: http://www.w3schools.com/html/html5_webstorage.asp

Community
  • 1
  • 1
Paul
  • 111
  • 5
  • That's because when you refresh the window, you're "leaving" the page. But that has led me to remember local storage which is essentially "sessions" for JavaScript: http://www.w3schools.com/html/html5_webstorage.asp You can use local storage for that browser session, and add that the user was already at the page, and only run the code if the session variable for local storage has not been set yet. – Paul Oct 31 '14 at 13:53
  • @Paul what will happen if he uses an older browser which doesn't support HTML5 ? – Md. Arafat Al Mahmud Oct 31 '14 at 14:34
  • There are other methods of tracking user state through JavaScript cookies, or server-side code with sessions or cookies depending on his intended use. – Paul Oct 31 '14 at 14:50
  • W3C is also promoting the use of HTML5 as the web standard so if he is using older browsers (does IE8 provide web storage?) then perhaps he should upgrade his browser. – Paul Oct 31 '14 at 14:53
1

If you set onbeforeunload callback, it will be executed every time whether you close the tab or refresh the page. So, lets get into some hack here. When we close the tab, the window loses its focus. So Inside onbeforeunload we will just check if the window has focus. If it has, you are refreshing the page. If it has lost focus, probably you have closed the tab.

window.onbeforeunload=function(){
    if(!document.hasfocus()){
        //show popup
    }
}
Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66