【问题标题】:Javascript/jQuery beforeunload and unload not firingJavascript/jQuery beforeunload 和 unload 不触发
【发布时间】: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


【解决方案1】:

环顾四周,我发现这非常好 answer - 我只需要把它放在我的 server.js 文件中:

peer.oniceconnectionstatechange = function() {
    if(peer.iceConnectionState == 'disconnected') {
        console.log('Disconnected');
    }
}

它确实需要几秒钟才能注册对等体已丢弃,但至少它总是在触发,这对我来说足够可靠。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多