用electron 打包的电脑软件 加了一个断网提示和联网发请求给后端做记录
javascript
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- <title><%= htmlWebpackPlugin.options.title %></title> -->
<title>吧台绿树电竞 - V1.0.0 店铺ID</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
<!-- built files will be auto injected -->
<!-- 页面内容 -->
<script>
let offlineTime = null;
// let nowtim = new Date()
window.addEventListener('online', () => {
const now = new Date();
if (offlineTime) {
const offlineDuration = now - offlineTime; // 离线时长(毫秒)
console.log(`网络重连成功,上次断网时间:${new Date(offlineTime).toLocaleString()}, 重连时间:${now.toLocaleString()}, 离线时长:${offlineDuration} 毫秒`);
alert(`网络重连成功,离线时长:${offlineDuration / 1000 / 60} 分钟`);
this.sendAjaxRequest() //断网时间
localStorage.setItem('nowTime', now.toLocaleString()); //重连
this.nowRequest()
} else {
console.log(`网络重连成功,之前没有断网记录`);
}
offlineTime = null; // 重置离线时间
});
window.addEventListener('offline', () => {
offlineTime = new Date(); // 记录断网时间
console.log(`当前断网,时间:${offlineTime.toLocaleString()}`);
localStorage.setItem('offlineTime', offlineTime.toLocaleString()); //断网
alert('当前断网');
});
// 断网
function sendAjaxRequest() {
var formData = new FormData();
formData.append('storeId', sessionStorage.getItem("storeId") || '');
formData.append('type', 0);
formData.append('ip', sessionStorage.getItem("ip") || '');
formData.append('createTime', offlineTime.toLocaleString() || '');
var xhr = new XMLHttpRequest();
xhr.open("POST", 'http://192.168.0.124:8091/bar/log/add', true);
xhr.onload = function () {
if (xhr.status === 200) {
} else {
console.error("Request failed. Returned status of " + xhr.status);
}
};
xhr.send(formData);
};
//重连
function nowRequest() {
let nowtim = new Date()
var Data = new FormData();
Data.append('storeId', sessionStorage.getItem("storeId") || '');
Data.append('type', 1);
Data.append('ip', sessionStorage.getItem("ip") || '');
Data.append('createTime', nowtim.toLocaleString() || '');
var xhrb = new XMLHttpRequest();
xhrb.open("POST", 'http://192.168.0.124:8091/bar/log/add', true);
xhrb.onload = function () {
if (xhrb.status === 200) {
console.log(xhrb.responseText);
} else {
console.error("Request failed. Returned status of " + xhrb.status);
}
};
xhrb.send(Data);
}
</script>
</body>
</html>
我是写在public- index.html 文件中 这样他只要是在运行中都可以 判断是否断网