检测关闭选项卡或浏览器脚本无效

时间:2015-05-13 06:39:28

标签: javascript jquery asp.net

我正在研究asp.net mvc应用程序。我遇到了我需要检测用户是否点击了关闭标签或浏览器的情况。我得到了下面的脚本,但是当用户提交表单时也会调用此脚本。例如在提交按钮上。我需要在关闭标签页或浏览器时可以运行的脚本。

脚本

(function($) {
    var refreshKeyPressed = false;
    var modifierPressed = false;
    var f5key = 116;
    var rkey = 82;
    var modkey = [17, 224, 91, 93];

    // Check for refresh keys
    $(document).bind('keydown',function(evt) {
        // Check for refresh
        if (evt.which == f5key || window.modifierPressed && evt.which == rkey) {
            refreshKeyPressed = true;
        }

        // Check for modifier
        if (modkey.indexOf(evt.which) >= 0) {
            modifierPressed = true;
        }
    });

    // Check for refresh keys
    $(document).bind('keyup', function(evt) {
        // Check undo keys
        if (evt.which == f5key || evt.which == rkey) {
            refreshKeyPressed = false;
        }

        // Check for modifier
        if (modkey.indexOf(evt.which) >= 0) {
            modifierPressed = false;
        }
    });

    $(window).bind('beforeunload', function(event) {
        var message = "not refreshed";

        if (refreshKeyPressed) {
            message = "refreshed";
        }

        event.returnValue = message;
        return message;
    });
}(jQuery));
$(window).bind('beforeunload', function(e) {
    return "If you close the window, your application with still be running. If you wish to stop the application, click 'cancel' and "
});

1 个答案:

答案 0 :(得分:2)

您应该使用onbeforeunload

  

窗口即将卸载其资源时触发的事件。该文档仍然可见,事件仍然可以取消。

window.onbeforeunload = function (e) {
    return 'Dialog text here.';
};

文档:https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload

修改

使用on代替bind。您正在使用bind在元素上附加事件。

$(window).on('beforeunload', function(e) {
    return "If you close the window, your application with still be running. If you wish to stop the application, click 'cancel' and "
});

修改-2

submit按钮将提交表单并刷新页面,除非您已阻止此操作。如果您想阻止这种情况发生,您应preventDefault提交表单或添加对unload事件的检查。

var submitting = false;
$('form').submit(function (e) {
    submitting = true;
    ...

});


$(window).bind('beforeunload', function (e) {
    if (!submitting) {
        return "If you close the window, your application with still be running. If you wish to stop the application, click 'cancel' and "
    }
    return false; // Prevent the alert box
});