0

I am using javascript function window detector onbeforeunload but it does not detect event when I click browser "close X" button. Is it problem in my code or it is its default behavior?

    $(window).on('unload onbeforeunload close', function (e) {
  e = e || window.event;

if (e) {

  if(localStorage.openpages==""||localStorage.openpages==null){
    var params = {
    isonline:0
  }
   $.ajax({
    async: false,
    type: "POST",
    url: '<?= base_url()?>UserProfile/setonlinestatus',
    data: params,
    contentType: "application/x-www-form-urlencoded",
    dataType: "json",
    timeout: 60000,
    success: function (response) {
        alert("")
    },
    error: function (jq, status, message) {
        var e = message;
    }
  });}
}});
//navigator.onLine it check whethe ri am online or not
Artier
  • 1,648
  • 2
  • 8
  • 22
  • Please have a look at: https://stackoverflow.com/questions/4945932/window-onbeforeunload-ajax-request-in-chrome - it should help you fix your issue – eithed Aug 22 '18 at 08:34
  • Detecting the closing of a browser is notoriously difficult. For example you won't get them if the browser crashes. You could use a keep alive mechanism whereby it keeps sending messages to you every minute. Then you'll know roughly how long the user has been online. They're offline if they've not updating within a few minutes. – R. Chappell Aug 22 '18 at 08:35
  • It work Ok when I close tab one by one – Artier Aug 22 '18 at 08:35
  • @eithed he actually does have async=false – mplungjan Aug 22 '18 at 08:35
  • You may want to use websockets – mplungjan Aug 22 '18 at 08:36
  • 1
    The last time I've had to deal with sending data on page close I've actually had to do it with async: true, but I think this has been changed by now. The answer I linked uses `navigator.sendBeacon()` which you can try out, as, looking at the docs, it should do what you want. – eithed Aug 22 '18 at 08:40
  • eithed Thank You so much `navigator.sendBeacon()` solve my issue – Artier Aug 22 '18 at 11:07
  • @Artier - no worries. I'd appreciate if you could answer your own question (or I can write up an official answer), in case somebody else stumbles upon this question and doesn't want to waddle through comments. Thanks! – eithed Aug 22 '18 at 19:58
  • @eithed Just convert ajax request to navigator sendbeaon() .. It also detect browser Close event – Artier Aug 22 '18 at 21:01
  • @Artier I meant - post an answer so the question doesn't stay open – eithed Aug 23 '18 at 14:51

1 Answers1

0

(unload and onbeforeunload) does not completed ajax request and browser close . we need to send same request through navigator.sendBeacon() method,This is used to asynchronously transfer a small amount of data over HTTP to a web server.

Artier
  • 1,648
  • 2
  • 8
  • 22