So I needed to do this so I could log a user out if they left the site from any page, but not if they navigate within the site. Here is my solution using JS and PHP
On every page where they need to remain logged in, set a session variable:
<?php
session_start();
$_SESSION["isInSession"] = true;
?>
Now create two scripts:
clear-in-session.php
<?php
session_start();
unset($_SESSION["isInSession"]);
?>
logout.php
<?php
session_start();
if(isset($_SESSION["isInSession"]) exit();
//do logout code here
?>
Now we set 2 events in JS:
window.addEventListener('beforeunload', function(event) {
$.ajax({
type: 'POST',
async: false,
url: 'clear-in-session.php'
});
});
window.addEventListener('unload', function(event) {
$.ajax({
type: 'POST',
async: false,
url: 'logout.php'
});
});
To explain the order of events when the user navigates to another page in the same site:
- The user navigates away
- beforeunload is triggered, calling clear-in-session.php which removes the isInSession variable
- The new page is loaded, setting isInSession to true
- unload is triggered, calling logout.php, but because isInSession has been set back to true, the logout code is never called
When the user navigates to a page outside of the site (or to any page on the site that doesn't set isInSession):
- The user navigates away
- beforeunload is triggered, calling clear-in-session.php which removes the isInSession variable
- The new page is loaded
- unload is triggered, calling logout.php, isInSession has been deleted, so the logout code is called
Sorry for necro but this thread still comes up when searching for the answer to this question
Note: This answer uses jQuery for post calls to the php. It is entirely possible to do this in pure JS, but it was easier to illustrate in jQuery