Im attempting to log the user activity in my database when they login and logout of the site. This works fine, but when they close the page via a tab or browser, there is no way to run the logout query, so according to the records the user never logs out of the site.

**Method 1:** 
I have tried `onbeforeunload`, but this does not seem to trigger before the page closes.

**Method 2:**
I would try the method of using an ajax keepalive token sent to the php, but this would need to run every 1 min and could cause high traffic load.

**Method 3:**
I was hoping an alterantive would be to set the `session.gc.maxlifetime` to 1 min and add a call to the logout query via a destroy session callback. 

Which would be the best method, or is there a better method of achieving this?

Is there a way to trigger a custom function(query) before php destroy session or php garbage collection has taken place? 

**UPDATE**

I have taken the advise of everyone and decided to attempt 'method 1'. So far this is my attempt but its still not working perfectly:

```
    var isClosePage = true; 

    //detect f5 and backspace page navigation
    $(document).on('keypress', function(e)
    {
        if (e.keyCode == 116) 
        {
            alert('f5');
            isClosePage = false;
        }
        if (e.keyCode == 8) 
        {
            alert('backspace');
            isClosePage = false;
        }
    });

    //detect back and forward buttons
    $(window).bind('statechange',function()
    {
        alert('back');
        isClosePage = false;
    });

    //detect page button press
    $('html').on('mouseenter', function() 
    {
        console.log('mouse has enetered!');
        isClosePage = false;
    });

    //detect browser buttons press
    $('html').on('mouseleave', function() 
    {
        console.log('mouse has left!');
        isClosePage = true;
    });

     //make ajax call (logout) to server if above events not triggered
     $(window).on('beforeunload', function(e)
     {
        if(isClosePage)
        {
             $.ajax(
             {
                  url:'php/function/active-user.php?logout=ajax',
                  dataType: 'jsonp',
                  crossDomain: true, 
                  async: false
             });

             //return 'some default message';
        }
        else
        {
            isClosePage = true;
        }
    });

```

Can anyone suggest any improvments to how I can make this work well?