有没有办法检测用户是否在beforeunload事件中按下“Stay on page”或“Leave page”?

时间:2013-07-20 07:08:05

标签: javascript jquery events event-handling onbeforeunload

我可以通过以下代码检测到用户点击“离开页面”或“留在页面上”按钮吗?

$(window).on('beforeunload', function (){
    return "You save some unsaved data, Do you want to leave?";
});

2 个答案:

答案 0 :(得分:12)

通过几次黑客攻击,您至少可以确定用户是否留下来 如果用户离开了页面,那么你无能为力:

var timeout;

$(window).on('beforeunload', function (){
    timeout = setTimeout(function() {
        // user stayed, do stuff here
    }, 1000);
    return "You save some unsaved data, Do you want to leave?";
});

FIDDLE

答案 1 :(得分:0)

iirc,当用户决定留在页面上时,不会触发卸载事件。这样:

$(window).on('unload', function (){
    // user has left the page, do stuff here
}