0

How can i know if the user click the right red close button in the browser and the close button of the tab

the idea is that i want when the user click the close red button or the close (X) of the tab a message appear to say are you sure you want to log out if he click yes he will be redirect to a logout page (i use php in this page) if not he will stay in the same page

i tried this code

window.onbeforeunload = function (e) {
    e = e || window.event;

    // For IE and Firefox prior to version 4
    if (e) {
        e.returnValue = 'Sure?';
    }

    // For Safari
    return 'Sure?';
}; 

but it didn't give me the result i want when i click on the red close button the browser close and when i click on a link a message appear

can any one help to do this ?!

user3942918
  • 25,539
  • 11
  • 55
  • 67
mohamad mohamad
  • 613
  • 9
  • 24
  • 1
    https://stackoverflow.com/questions/20853142/trying-to-detect-browser-close-event And https://stackoverflow.com/a/3888938/4248328 – Alive to die - Anant Aug 05 '17 at 06:42
  • your code behaves as expected in firefox, a popup appears - which asks to confirm closing the tab (oh, wait, closing the BROWSER is different to closing the TAB) – Jaromanda X Aug 05 '17 at 06:42
  • Javascript can't redirect when the user is trying to close the window. This is what adware used to do, to prevent the user from getting rid of the ads, so security changes were made to prohibit it. – Barmar Aug 05 '17 at 06:45
  • @Barmar you mean we can't detect when user click close ? – mohamad mohamad Aug 05 '17 at 06:49
  • You can detect it, but you can't redirect them to the logout page. All you can do is display a prompt asking if they're sure they want to close the window. If they say yes, the window closes. If they say no, nothing happens. – Barmar Aug 05 '17 at 06:53
  • @Barmar ok thank you like you say i can't do my idea because i can't redirect to a page when i click the red close button in the browser – mohamad mohamad Aug 05 '17 at 06:56

1 Answers1

-1

If you want to detect whether the user click the X on the top-right of the browser:

window.onbeforeunload = function (e) {
if(typeof e=='undefined'){
e=window.event;
}
// For IE and Firefox prior to version 4
if (e) {
    e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';

};

But I am also afraid you never catch the browser close event for the full 100%. For example, what if the user kills the browser process. Then the onUnload, or even the onBeforeUnload isn't called

Osama
  • 2,912
  • 1
  • 12
  • 15
  • 1
    This answer is full of obsolete and non-portable code. `window.event` doesn't exist in Firefox, `event.returnValue` is obsolete (just use a `return` statement). You also didn't show how to connect `handleWindowClose` to the event. – Barmar Aug 05 '17 at 06:55