How to detect browser or tab close event using JavaScript

To track the user online status, you need to maintain a flag in the database. You should need to update this flag when user will log out by the Logout link. If the user closes the browser without clicking the logout button, the browser close event detection would require for updating the flag in the database.

Using JavaScript onbeforeunload event, you can detect browser or tab close event and update the user online status in the database. The following JavaScript code could detect the browser close event as well as tab close event.

<script>
window.onbeforeunload = function(){
    //Ajax request to update the database
    $.ajax({
        type: "POST",
        url: "updateUserStatus.php"
    });
}
</script>

Leave a reply

keyboard_double_arrow_up