【发布时间】:2021-12-10 05:42:53
【问题描述】:
我有一个页面,我希望我的脚本在浏览器/选项卡/页面关闭时让服务器知道用户离线。
$(document).ready(function() {
// Inform the server that the user went online
setStatus('online');
// Inform the server that the user went offline
$(window).on('beforeunload', function() {
setStatus('offline');
});
// Inform the server that the user went offline
$(window).on('unload', function() {
setStatus('offline');
});
});
async function setStatus(status) {
let { data } = await axios.post('/status', { status: status });
}
我拥有setStatus('online'); 的部分有效,但当我关闭页面/选项卡/浏览器时,我似乎永远无法将状态设置为offline。
【问题讨论】:
-
尝试在卸载事件中执行异步操作从来都不是可靠的。尝试使用更现代的Navigator.sendBeacon()
标签: javascript jquery async-await axios