gpt4 book ai didi

javascript - 检测关闭选项卡或浏览器脚本不起作用

转载 作者:行者123 更新时间:2023-12-02 16:11:02 25 4
gpt4 key购买 nike

我正在开发 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 "
});

最佳答案

您应该使用onbeforeunload

An event that fires when a window is about to unload its resources. The document is still visible and the event is still cancelable.

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 "
});

EDIT-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
});

关于javascript - 检测关闭选项卡或浏览器脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30207387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com