0

I have question related to Browser close event..

How to capture the Browser close event without refresh event.

Thanks in Advance.

  • 1
    window.onbeforeunload = function(event) { // do something return null; }; – Niklesh Raut Aug 30 '17 at 14:24
  • 1
    Possible duplicate of [javascript detect browser close tab/close browser](https://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser) – pritaeas Aug 30 '17 at 14:31
  • I have tried using window.onbeforeunload function which will work for both close and refresh events at time.so it didn,t work. – Rajasekhar Aug 30 '17 at 14:33
  • There is no built in way. But an idea, not tried myself. But on your onunload event, store the current datetime inside localstorage, and then on page load if the difference in time is say less than a second, you could assume it's a refresh. – Keith Aug 30 '17 at 15:07
  • Thanks keith for your replay.. – Rajasekhar Aug 31 '17 at 07:31

2 Answers2

0

Using window.onbeforeunload but this will also be triggered when you reload the browser or moving to a different page by clicking on a link.

window.onbeforeunload = function(e) {
  var dialogText = 'Dialog text here';
  e.returnValue = dialogText;
  return dialogText;
};

Note: window.onbeforeunload will not work on touch devices except Android.

Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
0

Try this one

window.onbeforeunload = function (event) {
    var message = 'Important: Please click on \'Save\' button to leave this page.';
    if (typeof event == 'undefined') {
        event = window.event;
    }
    if (event) {
        event.returnValue = message;
    }
    return message;
};

$(function () {
    $("a").not('#LogOut').click(function () {
        window.onbeforeunload = null;
    });
    $(".btn").click(function () {
        window.onbeforeunload = null;
});
});
Kuzenko Lubko
  • 1,961
  • 1
  • 20
  • 26