4

I have a javascript function to fire when page/browser close like this:

  window.onbeforeunload = function (e) {

    var y = window.event.clientY;// e.pageY || e.clientY;

    if (y < 0) {

        alert('Window closed');

    }
    else {
        alert('Window refreshed');

    }

The function work fine IE but not in other browsers. I want to fire this function only at browser/tab close of a webpage. Not in the page refresh/reload.

Please help.

Praveen VR
  • 1,554
  • 2
  • 16
  • 34

1 Answers1

2

The function work fine IE but not in other browsers.

That's absolutely normal. Other browsers simply do not allow you to be alerting in this function.

Check that fiddle out in Chrome:

enter image description here

Sorry, you should forget about alerting in an onbeforeunload handler. The only thing you should be doing in this handler is returning a string result:

window.onbeforeunload = function (e) {
    var y = window.event.clientY;// e.pageY || e.clientY;
    if (y < 0) {
        return 'Window closed';
    }
    else {
        return 'Window refreshed';
    }
};

It's the responsibility of the browser to decide how to display this information to the user, not you by telling it to explicitly alert.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Actually I want o execute an ajax call in while closing the form/browser. Should it work in this scenario? – Praveen VR Jun 20 '13 at 10:58
  • 1
    That's not guaranteed. If the user clicks on the Close button very quickly the browser will simply redirect away from the page stopping all javascript execution and if your AJAX request didn't make it to the server, well, it might never make it. I wouldn't rely on such behavior. – Darin Dimitrov Jun 20 '13 at 11:00