Javascript:在 onbeforeunload 上抑制 "This page is asking you to confirm that you want to leave"弹出窗口

标签 javascript ajax onbeforeunload

当用户离开页面时,我需要在离开前询问他是否要执行特定操作。

<script type="text/javascript">
$(document).ready(function() {
        window.onbeforeunload = askConfirm;
});

function askConfirm() {
    var addFriend = confirm("Would you like to ping?");
    if (addFriend) {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp=new XMLHttpRequest();
        } else {
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET","http://example.com?ping=1234",true);
        xmlhttp.send();
    }
    return null;
}

取决于最后一个 return 语句的值(""nulltruefalse,或者根本没有 return 语句)我可能遇到以下两种情况之一:

1) 用户得到“你想ping吗?”确认(好),发送 ping(好),用户看到“此页面要求您确认是否要离开”弹出窗口(坏)

-或-

2) 用户得到“你想ping吗?”确认(良好),ping 发送(错误),并且用户显示“此页面要求您确认您要离开”弹出窗口(好)。

我怎样才能发送 AJAX ping,同时抑制“此页面要求您确认是否要离开”弹出窗口?

编辑:虽然听起来很荒谬,但我发现针对此问题的“变通办法”是在 xmlhttp.send( ) 语句。唯一干净的方法是提醒用户他的 ping 已发送。如果 future 的 StackOverflowers 找到更好的解决方案,我很想知道。

谢谢。

最佳答案

您可以使 Ajax 请求同步。

xmlhttp.open("GET","http://example.com?ping=1234", false); // use false here 
xmlhttp.send(); 

如果您的服务器速度较慢,可能会造成轻微的延迟,但它应该可以解决无法发送 ping 的问题。

关于Javascript:在 onbeforeunload 上抑制 "This page is asking you to confirm that you want to leave"弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9219800/

相关文章:

javascript - onBeforeUnload 没有被 headless 浏览器触发

javascript - 在 onbeforeunload 事件的窗口确认时调用回调函数

javascript - knockout ,映射后从 View 模型中获取JSON

javascript - 如何使用给定行的 html 表中的输入字段创建动态行

javascript - 如何在 jQuery DataTable 中将列数据设为超链接

javascript - 如何通过 Jquery 和 ajax 从响应中下载 JSON 文件

javascript - 有没有办法在 iOS 设备的 Mobile Safari 上使用 window.onbeforeunload ?

Javascript_Java_Interaction 小程序 "Codebase"问题

javascript - 较短页面上的粘性导航问题

ajax - 使用浏览器缓存的增量更新