禁用返回按钮,直到回调执行

AJAX Disable back button until callback executes

本文关键字:回调 执行 返回 按钮      更新时间:2023-09-26

我有一个代码错误弹出时,有人点击后退按钮,而ajax调用正在加载。是否有一种方法可以在调用成功返回之前禁用back ?

的例子:

$.ajax({
// Disable back button
url: "test.html",
context: document.body
}).done(function() {
// Enable back button
$(this).addClass("done");
});

我知道劫持浏览器功能是不好的,我注意到,但这不是我的选择在这里,我不是项目所有者。此外,它只是暂时的几秒钟,而ajax做它的事情。我已经搜索过了,但还没有找到任何对这个场景特别有用的东西。

您不能禁用浏览器中的后退(或任何)按钮。你能想象如果你能吗?垃圾邮件弹窗将有一个field day!

无论如何,你能做的最好的是使用onbeforeunload(它只在某些浏览器中工作,就像我知道Opera不支持它)。如果有AJAX请求,您可以抛出"您确定要离开吗?"消息。

的例子:

$(document).ajaxStart(function(){
    $(document.body).addClass('running');
});
$(document).ajaxStop(function(){
    $(document.body).removeClass('running');
});
$(window).on('beforeunload', function(){
    if($(document.body).hasClass('running')){
        return "There is still a pending AJAX request.  Are you sure you want to leave?";
    }
});
$.ajax({
    url: "test.html",
    context: document.body
}).done(function() {
    $(this).addClass("done");
});

您无法阻止用户在WebBrowser中使用后退按钮,但也许您可以使用此代码向用户发出等待的信号。(也许用户等待,或者等待):)

的例子:

window.onbeforeunload = function(){
     return "Please wait until page load is done?";
}

=> Chrome 26+测试代码

也许这有帮助

编辑:

为了对抗"hop"提到的内容,您可以在开始ajax调用时设置此事件函数,并在结束ajax调用后删除该函数,但这只是一些细节。

示例2:

 ...
 function setPreventLeavingPage(){
    window.onbeforeunload = function(){
         return "Please wait until page load is done?";
    }
 }
 function removePreventLeavingPage(){
   window.onbeforeunload = null;
 }
 ...
 $.ajax({
    url: "test.html",
    beforeSend: function() {
      setPreventLeavingPage();
    },
    context: document.body
    }).done(function() {
       // do some stuff
       ...
       removePreventLeavingPage();
    });

=>代码测试在Chrome 26 +

当你在完成函数中添加类时,你可能想检查'this'变量在什么上下文中。我的猜测是,它是指向窗口在你做的功能,而不是你的按钮。

.done(function(){console.log(this);});