javascript - 如何在没有用户交互的情况下捕获标签关闭事件
问题描述
基本上我试图在页面关闭时保存一些数据,即使没有用户交互。我试过使用 onbeforeunload 监听器:
window.onbeforeunload = function (event) {
event.preventDefault();
const requestData = {
parameter : 'test',
step: 2
};
fetch('/send-data', {
method : 'POST',
headers: new Headers({'content-type': 'application/json'}),
body : JSON.stringify(requestData)
})
return undefined;
};
我曾希望,因为我没有打开一个对话框,所以我能够使用该事件,但它只能通过用户交互来调用。有没有办法在标签/窗口关闭时捕获事件(或任何其他)以发送/保存一些数据?也可以使用 jquery。
解决方案
推荐阅读
- javascript - 为什么这个js函数返回未定义的对象?
- python - Python3 tkinter DLL 加载失败
- python - 通过示例了解 LSTM
- php - 让孙子们用 Laravel eloquent 建模
- reactjs - 如何在 React Native + TypeScript 中从孙子更改祖父组件的状态?
- python - 如何让不和谐的机器人获取昵称而不是用户名?
- julia - 为什么加号运算符在 Julia 中被矢量化,而不是除法运算符?
- git-merge - 从两个存储库之间的合并创建一个 Yocto 层
- java - Java:如何从保存在路径中的多个文件夹中提取最大名称到文件夹名称都是数字的变量中?
- matlab - 如何改进这两个功能以减少给出结果的时间?