vje*_*eta 60 javascript browser jquery
我已经尝试了很多方法来通过jQuery或JavaScript检测浏览器关闭事件.但是,不幸的是,我无法发现关闭.这些onbeforeunload和onunload方法也不起作用.
如何检测的窗口close,unload或beforeunload事件?
Rav*_*lya 69
你试过这段代码吗?
window.onbeforeunload = function (event) {
var message = 'Important: Please click on \'Save\' button to leave this page.';
if (typeof event == 'undefined') {
event = window.event;
}
if (event) {
event.returnValue = message;
}
return message;
};
$(function () {
$("a").not('#lnkLogOut').click(function () {
window.onbeforeunload = null;
});
$(".btn").click(function () {
window.onbeforeunload = null;
});
});
Run Code Online (Sandbox Code Playgroud)
第二个函数是可选的,以避免在单击#lnkLogOut和.btn元素时提示.
还有一件事,自定义提示在Firefox中不起作用(即使在最新版本中也是如此).有关它的更多详细信息,请转到此主题.
小智 43
参考各种文章并进行一些试验和错误测试,最后我发展了这个对我来说完美的想法.
我们的想法是检测关闭浏览器触发的卸载事件.在这种情况下,鼠标将离开窗口,指向关闭按钮('X').
$(window).on('mouseover', (function () {
window.onbeforeunload = null;
}));
$(window).on('mouseout', (function () {
window.onbeforeunload = ConfirmLeave;
}));
function ConfirmLeave() {
return "";
}
var prevKey="";
$(document).keydown(function (e) {
if (e.key=="F5") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "W" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "R" && prevKey == "CONTROL") {
window.onbeforeunload = ConfirmLeave;
}
else if (e.key.toUpperCase() == "F4" && (prevKey == "ALT" || prevKey == "CONTROL")) {
window.onbeforeunload = ConfirmLeave;
}
prevKey = e.key.toUpperCase();
});
Run Code Online (Sandbox Code Playgroud)
ConfirmLeave函数将提供弹出的默认消息,以防需要自定义消息,然后在函数ConfirmLeave()中返回要显示的文本而不是空字符串.
Kha*_*lla 11
在Linux chrome环境下尝试以下代码适用于我.在运行之前,请确保将jquery附加到文档.
$(document).ready(function()
{
$(window).bind("beforeunload", function() {
return confirm("Do you really want to close?");
});
});
Run Code Online (Sandbox Code Playgroud)
简单地按照以下步骤操作:
它应该显示以下图片:

以下脚本将在 Chrome 和 IE 上给出消息:
<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here
return "Please click 'Stay on this Page' and we will give you candy";
};
</script>
Run Code Online (Sandbox Code Playgroud)
铬合金
IE

在 Firefox 上,您将收到通用消息

机制是同步的,因此服务器调用延迟不会起作用,您仍然可以准备一种机制,例如模式窗口,如果用户决定留在页面上,则显示该窗口,但无法阻止他离开。
回复评论中的问题
F5将再次触发事件,因此Atl+也会发生F4。
| 归档时间: |
|
| 查看次数: |
266823 次 |
| 最近记录: |