【发布时间】:2021-02-22 15:56:46
【问题描述】:
我正在尝试在窗口关闭时发送数据,以防止 2 个人编辑和覆盖彼此的数据。目前我在卸载事件处理程序中使用 sendBeacon。
火狐:
- 刷新:作品
- 返回按钮:有效
- 关闭窗口:作品
铬:
- 刷新:作品
- 返回按钮:有效
- 关闭窗口:不起作用
这是我的代码
function sendDataOnClose(edit,trans){
var url = "../../save.php"; //This has a post request handler and works properly with other functions for saving data
const data = JSON.stringify
({
"translations": trans,
"edit": edit
});
navigator.sendBeacon(url, data);
}
function handleClose(){
if(edit){
console.log("sending a false when edit is: "+ edit)
sendDataOnClose(false, translations);
}
}
window.addEventListener('unload', handleClose);
【问题讨论】:
-
即使文档显示
unload and beforeunload aren’t the right events to use with sendBeacon. Instead, use visibilitychange.它也不能在关闭visibilitychange事件时起作用! -
@webdevtrev 它适用于所有主流浏览器的最新版本,我最近测试过。你可以查看这个帖子:https://stackoverflow.com/a/69955104/1786360
标签: javascript php google-chrome onunload sendbeacon