skip to Main Content

I am working on a site and currently encounter a problem, i have a user who would be a rider when he comes to my website he must be marked active and when he leaves he must be mark in-active. Well i am able to mark him active and even in-active when he properly log out.
But what if he close the browser or the tab. Secondly my web app will mostly be run on mobile phone so what if the rider switch between browser and some other app.
I have already tried

window.onbeforeunload = function(event) {
        //My Ajax Request
});

window.addEventListener("unload", function(event) {
        //My Ajax Request
});

but its work great on firefox but only work sometimes on chrome and internet explorer and is not reliable.

I was hoping someone could guide me for any better and reliable approach.

2

Answers


  1. Try these approaches:

    window.addEventListener("beforeunload", function(event) {
        //My Ajax Request
    });
    
    window.attachEvent("beforeunload", function(event) {
        //My Ajax Request
    });
    

    Also, use event.preventDefault() before doing your AJAX request.

    Login or Signup to reply.
  2. unload and beforeunload are not considered reliable for Ajax request. you could choose short polling – sending indication to the to server (eg. every x seconds/mins) about user being active. mark user active/inactive based on that.

    for switching between tab /mobile apps. you could use windows blur event to indicate the same .

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search