0

I'm wondering what methods could be used to detect when a browser window, or tab just before it is closed?

I'm guessing there are a few ways, but I'm not sure of the best.

I've seen spam sites that give a pop up window saying "are you sure you want to exit" before the browser window will close. Anyone know how to achieve this in code? Would javascript be the only/best solution?

Tracking the mouse (when it moves to top right hand corner) might be a good way, again in probably only in javascript?

Perhaps cookies can do this?

Any thoughts or suggestions would be wonderful.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
Ke.
  • 2,484
  • 8
  • 40
  • 78
  • https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload – Marc B Jun 26 '15 at 21:56
  • the follow stackoverflow post should help. http://stackoverflow.com/questions/14645011/window-onbeforeunload-and-window-onunload-is-not-working-in-firefox-safari-o – dshun Jun 26 '15 at 21:58
  • possible duplicate of [javascript detect browser close tab/close browser](http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser) – JJJ Jun 26 '15 at 22:00

2 Answers2

2

You can use onbeforeunload event:

window.addEventListener('beforeunload',function(){
   alert('closing');
});

Or,

window.onbeforeunload = function(){
   alert('closing');
};

If you want to prevent default behavior then you can use it like below:

window.addEventListener("beforeunload", function (e) {
  var confirmationMessage = "\o/";

  (e || window.event).returnValue = confirmationMessage;     //Gecko + IE
  return confirmationMessage;                                //Webkit, Safari, Chrome etc.
});

see docs

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231
0
 window.onbeforeunload = function () {
        return "Do you really want to close the page?";
    }

Put any of your code within that function to run when a user is about to close the page

Tomi
  • 116
  • 5