More recently, this has worked for me; however you need to watch for browser compatabilty.
document.addEventListener('visibilitychange', function() {
if (document.hidden) {
// Perform logout action here
// window.location.href = 'logout.php';
}
});
https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilitychange_event