1

Is it possible to detect if the browser is closing in JavaScript? I tried using:

$( window ).unload(function() {
    //Code
});

and:

window.onbeforeunload = ExecuteMyCode;
function ExecuteMyCode() {
    //Code
}

But this both executes when we also click a link, button,... I ONLY want to detect the browser close event.

tshepang
  • 12,111
  • 21
  • 91
  • 136
RubenHerman
  • 1,674
  • 6
  • 23
  • 42
  • button? What button? A browser button? I think you can only detect when a user moves away from your current page / website. Not when the browser is actually closed. Why would you want that anyway? – putvande Jan 29 '14 at 12:18
  • I need it to remove my cookies before closing (and setting a time for the cookie isn't an option) – RubenHerman Jan 29 '14 at 12:20
  • If you just set the cookies as session cookies then these will automatically be removed by the browser when it closes anyway - what you are describing is default behaviour. – pwdst Jan 29 '14 at 12:23
  • What you could do is check with the `beforeunload` if someone is moving away from your website (so to new website or close the tab / browser). Than you can remove your cookie. – putvande Jan 29 '14 at 12:23
  • @putvande how do you do that? There doesn't seem to be an obvious way to determine where the user is going. Only that they're leaving... – uesports135 Apr 13 '15 at 15:43

1 Answers1

-1

You can try below code it will ensure your mouse position is on the close button then and then it will execute further.

window.onbeforeunload = function () {

            if (event.clientY < 0) {
                // DO YOUR STUFF BEFORE CLOSING..
            }
                return "Message to display user before close.";
            }
}