1

I was looking for a similar answer in the questions on the portal, but I could not reach the goal. What I am trying to do is update a table when closing the browser, with an AJAX function, this works in Firefox, it doesn't work in Chrome. How can I make it compatible with Chrome.

  <?php 
//session_start();
require_once 'Connections/swag.php';
$connection = new swag();
    if(!isset($_SESSION["id_user"])){ 
        echo"<script>location.href='index.php';</script>";  
    } ?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/styles.css">
    <link rel="shortcut icon" href="imgs/icon/favicon.ico">
    <title>PAG</title>
    <link href="font-awesome/css/all.min.css" rel="stylesheet"> 
</head>
<body id="principal">

        
<script src="js/jquery-3.5.1.min.js"></script>
<script type="text/javascript">

//Detect Browser or Tab Close Events
$(window).on('beforeunload',function(e) {
  e = e || window.event;
  var localStorageTime = localStorage.getItem('storagetime')
  if(localStorageTime!=null && localStorageTime!=undefined){
    var currentTime = new Date().getTime(),
        timeDifference = currentTime - localStorageTime;

    if(timeDifference<25){//Browser Closed
       localStorage.removeItem('storagetime');
        $.ajax({
        type: 'post',
         url: 'logout.php',
       });
    }else{//Browser Tab Closed
       localStorage.setItem('storagetime',new Date().getTime());
        $.ajax({
        type: 'post',
         url: 'logout.php',
       });
    }

  }else{
    localStorage.setItem('storagetime',new Date().getTime());
  }
});
    </script>
<script src="js/bootstrap.bundle.min.js"></script>  
<script src="js/utiles.js"></script>
</body>
</html>
  • Have you tried `blur` event? – jacobkim Aug 20 '21 at 02:51
  • Yes, I have tried several ways, I asked a similar question with another code, but did not receive any comments. https://stackoverflow.com/questions/68854636/how-to-detect-event-when-exiting-browser-with-js – julio fernandez Aug 20 '21 at 03:17
  • With `blur` , there is a detail, when updating with the browser button in Chrome it detects the event and updates the table, in the same way when reloading the page with the URL – julio fernandez Aug 20 '21 at 03:20
  • Does this answer your question? [window.onbeforeunload not working in chrome](https://stackoverflow.com/questions/4802007/window-onbeforeunload-not-working-in-chrome) – CodeBug Aug 20 '21 at 07:39

0 Answers0