How do google analytics detect the user leaves page?

Google Analytics does not detect when somebody leaves the page. There is no reliable way to do that (unload handlers do not fire when somebody just closes the window). Instead Google waits till the session has ended - after 30 minutes without interaction (can be adjusted in Universal Analytics in the property settings) the session is ended and the vsitor has left as far as the reports are concerned (he might have left a lot earlier, but the time after the last interaction is not tracked in GA).

Plus a session can have 500 interactions at maximum, so there is no way to keep it alive indefinitely.


Eike Pierstorff already gave a good answer for my question, just wanted to add some details found on google analytics documentation and a complementary solution to fine tuning the session cookie timeout.

Beside setting the session cookie timeout on the account settings under: admin > property > tracking info > session settings

It can also be set on runtime:

_gaq.push(['_setSessionCookieTimeout', 1800000]);

You can find more details on the google documentation.

_setSessionCookieTimeout(cookieTimeoutMillis)

Sets the new session cookie timeout in milliseconds. By default, session timeout is set to 30 minutes. Session timeout is used to compute visits, since a visit ends after 30 minutes of browser inactivity or upon browser exit. If you want to change the definition of a "session" for your particular needs, you can pass in the number of milliseconds to define a new value. This will impact the Visits reports in every section where the number of visits are calculated, and where visits are used in computing other values. For example, the number of visits will increase if you shorten the session timeout, and will decrease if you increase the session timeout. You can change the expiration timeout to 0 to indicate that this cookie should be deleted when the browser is closed.