vue3 监听浏览器窗口关闭事件,在窗口close前发送一个请求记录下使用记录这样子。
但是实际使用过程中发现有时候调请求存记录会不成功,并不是每次在使用完关闭窗口后都成功的存了使用记录。
请问是由于请求完成前浏览器已经关闭了导致请求取消造成的嘛?如果是的话,该如何确保在窗口关闭前,发送后台请求,且确保能请求执行完成呢?
代码如下:
//监听 浏览器窗口关闭事件,触发日志上传
onMounted(() => {
window.addEventListener("beforeunload", (e) => beforeunloadHandler(e));
window.addEventListener("unload", (e) => unloadHandler(e));
});
onUnmounted(() => {
window.removeEventListener("beforeunload", (e) => beforeunloadHandler(e));
window.addEventListener("unload", (e) => unloadHandler(e));
});
const beforeunloadHandler = async (event: any) => {
if (state.totalPressCount > 0) {
logEndTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');//add2023-07-25 plq
// await submitAlarmCaseToolLog();
}
//网页上 显示确认对话框
// Cancel the event as stated by the standard.
// event.preventDefault(); // 取消默认的关闭操作
// Chrome requires returnValue to be set.
// event.returnValue = ""; // Chrome要求设置返回值才能触发提示框
}
const unloadHandler = async (event: any) => {
if (state.totalPressCount > 0) {
// logEndTime.value = dayjs().format('YYYY-MM-DD HH:mm:ss');//add2023-07-25 plq
await submitAlarmCaseToolLog();
}
}
//添加事件工具使用记录 add2023-07-25 plq
const submitAlarmCaseToolLog = async () => {
const _requestData = {
alarmCaseId: alarmCase_store.alarmCaseData?.id as number,
toolKitId: guidanceToolsIdEnum.cpr_guide_tool,
openTime: logStartTime.value,
closeTime: logEndTime.value,
resultId: "",
resultName: `累计按压计数:${state.totalPressCount}`,
assessFlowId: paramAssessFlowId.value,//问题关联工具 add2023-07-27 plq
orderId: paramAssessOrderId.value,
guidanceStepId: paramStepId.value, //指导步骤关联工具
guidanceStepSourceId: paramStepSourceId.value,
};
let _res = (await addAlarmCaseToolLog(_requestData)).data;
// console.log(_res);
};