vue3 监听浏览器窗口关闭事件,该如何实现在窗口close前发送请求记录日志,并确保后台请求一定能执行完成?

作者站长头像
站长
· 阅读数 4

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);
};
回复
1个回答
avatar
test
2024-06-21
  window.addEventListener('beforeunload', () => {
    let blob = new Blob([JSON.stringify(params)], {
      type: 'application/json',
    });
    navigator.sendBeacon(window.location.origin+'请求路径',blob);
  })
  window.addEventListener("unload", () => { //部分手机可以获取到
 
    let blob = new Blob([JSON.stringify(params)], {
      type: 'application/json',
    });

    navigator.sendBeacon(window.location.origin+'请求路径',blob);
  })
  window.addEventListener("pagehide", () => {
    clearInterval(timer)
    let blob = new Blob([JSON.stringify(params)], {
      type: 'application/json',
    });
    localStorage.setItem('pagehide','pagehide')
    navigator.sendBeacon(window.location.origin+'请求路径',blob);
  },false);
  document.addEventListener("visibilitychange", () => {
    clearInterval(timer)
    let blob = new Blob([JSON.stringify(params)], {
      type: 'application/json',
    });
    localStorage.setItem('visibilitychange','visibilitychange')
    navigator.sendBeacon(window.location.origin+'请求路径',blob);
  })
  window.addEventListener("visibilitychange", () => {

    let blob = new Blob([JSON.stringify(params)], {
      type: 'application/json',
    });
    localStorage.setItem('winvisibilitychange','visibilitychange')
    navigator.sendBeacon(window.location.origin+'请求路径',blob);
  })
回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容