javascript - 使用JS退出浏览器时如何检测事件?
问题描述
我试图在退出浏览器时捕获一个事件,以便更新带有状态列的表,我设法用 JS 做到了,但我有一个细节,在 Firefox 浏览器中它可以工作,但在 Chrome 中有使用浏览器按钮重新加载页面或重新加载在 URL 内输入时的一个小细节会检测到它是否已退出。
使用按钮和 URL 重新加载页面时如何跳过此事件
这是我的代码,我们很乐意接受任何建议。
<?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">
$(document).ready(function(){
var validNavigation = false;
// Attach the event keypress to exclude the F5 refresh (includes normal refresh)
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
$(document).keydown(function(e) {
if (e.keyCode == 65 && e.ctrlKey) {
validNavigation = true;
}
});
$(document).keydown(function(e) {
if (e.keyCode == 65+17 && e.ctrlKey) {
validNavigation = true;
}
});
$(document).keydown(function (e) {
if (e.key=="F5") {
validNavigation = true;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
validNavigation = true;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
validNavigation = true;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
});
window.onbeforeunload = function() {
if (!validNavigation) {
$.ajax({
type: 'post',
url: 'logout.php',
});
}else{
}
};
});
</script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/utiles.js"></script>
</body>
</html>