2

The idea is to show a customized popup / div when user closes the browser. Found this code online and it works for me partially.

JS:

window.onbeforeunload = function (e) {            
            e = e || window.event;
            if (e) {
                e.returnValue = '';
                $("#popup").show();
            }            
        }

HTML:

<div id="popup" class="popup">
</div>

When user closes the browser, an alert pops up with a confirmation, to leave or stay. Is it possible to show the popup/div without showing the default JS alert.

This piece of code also fires when user refreshes the page. How to allow this only on close event.

sukesh
  • 2,379
  • 12
  • 56
  • 111
  • Use `e.preventDefault()` to avoid showing the default JS alert... – Rakesh_Kumar Feb 17 '15 at 09:24
  • Possible duplicate of http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser or http://stackoverflow.com/questions/17831683/how-to-trigger-a-browser-window-or-tab-close-event-with-jquery – Ravi Jiyani Feb 17 '15 at 09:29
  • `e.preventDefault()` did not work – sukesh Feb 17 '15 at 09:36

1 Answers1

0

Only works in the more recent browsers to ignore the alert with a return if you don't use jquery:

window.onbeforeunload = function (e) {            
     e = e || window.event;
     if (e) {
         $("#popup").show();
     }

    return null;        

}

Events (e), actually never should be edited

Drifter
  • 281
  • 1
  • 9
  • Tried this in chrome version 40. no change at all. The default JS alert still pops and it also pops on page refresh – sukesh Feb 17 '15 at 09:34
  • Ah Tested in jsfiddle. I see the problem, see update, 'removed the e.returnValue' http://jsfiddle.net/hk667thh/1/ – Drifter Feb 17 '15 at 09:37
  • _“The default JS alert still pops and it also pops on page refresh”_ – and that is exactly what is to be expected. You are not supposed to execute more intricate code of your own on `beforeunload` – you are limited to having the browser ask the user whether or not they want to leave the page (with a text that you can specify) by design. – CBroe Feb 17 '15 at 09:52
  • @user3790680. The new edit neither shows alert nor the div. Just closes the browser. – sukesh Feb 17 '15 at 10:03