在浏览器中检测后退按钮

fac*_*ook 73 javascript jquery

我必须检测用户是否点击了后退按钮.为此,我正在使用

window.onbeforeunload = function (e) {
}
Run Code Online (Sandbox Code Playgroud)

如果用户单击后退按钮,它可以工作.但是,如果用户单击F5或重新加载浏览器按钮,也会触发此事件.我该如何解决?

Gus*_*ord 63

所以就AJAX而言......

使用大多数使用AJAX的网络应用程序按回来浏览页面的特定部分是一个巨大的问题.我不接受"必须禁用按钮意味着你做错了什么",事实上,不同方面的开发人员长期遇到这个问题.这是我的解决方案:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)

至于我已经能够告诉这个工作跨chrome,firefox,还没有测试IE.


Ben*_*uer 60

请尝试这个(如果浏览器不支持"onbeforeunload"):

jQuery(document).ready(function($) {

  if (window.history && window.history.pushState) {

    $(window).on('popstate', function() {
      var hashLocation = location.hash;
      var hashSplit = hashLocation.split("#!/");
      var hashName = hashSplit[1];

      if (hashName !== '') {
        var hash = window.location.hash;
        if (hash === '') {
          alert('Back button was pressed.');
        }
      }
    });

    window.history.pushState('forward', null, './#forward');
  }

});
Run Code Online (Sandbox Code Playgroud)

  • 非常有用的代码,但是,正如@Portekoi指出的那样,不会阻止两次后退按钮.为了实现完全阻塞功能,我在`alert('...')`行之后添加了最后一行`window.history.pushState('forward',null,'./#forward')`.这样做了诀窍......没有刷新或对后退按钮点击有任何明显的影响. (2认同)

小智 8

我知道的最佳方式

         window.onbeforeunload = function (e) {
            var e = e || window.event;
            var msg = "Do you really want to leave this page?"

            // For IE and Firefox
            if (e) {
                e.returnValue = msg;
            }

            // For Safari / chrome
            return msg;
         };
Run Code Online (Sandbox Code Playgroud)

  • 这在 Chrome 中不起作用。 (2认同)
  • 这不会“禁用”后退按钮,因为它会阻止任何浏览(后退、前进、刷新),并允许用户通过超出您控制范围的提示来停止它。 (2认同)

Ale*_*dra 6

我通过这种方式检测后退按钮:

window.onload = function () {
if (typeof history.pushState === "function") {
    history.pushState("jibberish", null, null);
    window.onpopstate = function () {
        history.pushState('newjibberish', null, null);
        // Handle the back (or forward) buttons here
        // Will NOT handle refresh, use onbeforeunload for this.
    };
}
Run Code Online (Sandbox Code Playgroud)

它可以工作但我必须在Chrome中创建一个cookie来检测我第一次进入页面,因为当我在没有cookie控制的情况下进入页面时,浏览器会执行后退操作,而无需单击任何后退按钮.

if (typeof history.pushState === "function"){
history.pushState("jibberish", null, null); 
window.onpopstate = function () {
    if ( ((x=usera.indexOf("Chrome"))!=-1) && readCookie('cookieChrome')==null ) 
    {
        addCookie('cookieChrome',1, 1440);      
    } 
    else 
    {
        history.pushState('newjibberish', null, null);  
    }
};
Run Code Online (Sandbox Code Playgroud)

}

非常重要,history.pushState("jibberish", null, null);重复浏览器历史记录.

有人知道我能修复它吗?


bpe*_*n76 3

我假设您正在尝试处理 Ajax 导航,而不是尝试阻止用户使用后退按钮,这几乎违反了 UI 开发的所有原则。

以下是一些可能的解决方案:

  • @ibh:也许 [Post/Redirect/Get (PRG) 模式](http://en.wikipedia.org/wiki/Post/Redirect/Get) 适合您的需求。 (3认同)
  • 如果您只是让他们进入该页面,但在单击按钮时设置一个变量(或会话或 cookie)来告诉应用程序不再显示表单,这不是更容易吗?您可以简单地隐藏表单并提供另一个“感谢您已经填写表单页面”,或者,如果已设置该变量,则自动重定向。这也会阻止他们按照原来的方式航行。 (3认同)