【问题标题】:detect back button click in browser [duplicate]检测浏览器中的后退按钮单击[重复]
【发布时间】:2011-09-15 14:29:36
【问题描述】:

我必须检测用户是否点击了返回按钮。 为此,我正在使用

window.onbeforeunload = function (e) {
}

如果用户单击后退按钮,它会起作用。但是如果用户单击 F5,也会触发此事件 或浏览器的重新加载按钮。我该如何解决这个问题?

【问题讨论】:

  • 你读了吗stackoverflow.com/questions/680785/…>
  • 您可以在 [此处][1] 找到答案。 [1]:stackoverflow.com/a/16603692/668572
  • :( 我无法为重复的问题添加答案...无论如何,这可以通过window.performance && window.performance.navigation.type == 2 完成(检测后退按钮)

标签: javascript jquery


【解决方案1】:

就 AJAX 而言...

在使用大多数使用 AJAX 导航页面特定部分的 Web 应用程序时按回是一个巨大的问题。我不接受“必须禁用按钮意味着你做错了什么”,事实上,不同方面的开发人员早就遇到了这个问题。这是我的解决方案:

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

据我所知,这适用于 chrome、firefox,尚未测试 IE

【讨论】:

  • 这使用History API 而不是supported everywhere。您可以添加shim,但您必须更改一些代码。
  • 你完全正确。我查了一下,我可以让旧的 FF 和 IE 使用这个模型..(上面编辑)看看这个人的帖子:adequatelygood.com/2010/7/Saner-HTML5-History-Management
  • 我的解决方案有点太简单了,您的链接引用了一个很棒的跨平台解决方案我相信基于相同的 hashchange 事件。
  • 1.如果您只想捕获事件但保留原始后退按钮行为,则应在 window.onpopstate 事件中添加history.go(-2);。 2.我认为window.onhashchange只有在URL包含“#”锚时才有效
  • 如果地址中没有哈希值(onhashchange 事件永远不会触发),这在 IE9 中将不起作用。不要忘记在注册事件之前添加默认哈希。
【解决方案2】:

请试试这个(如果浏览器不支持“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');
  }

});

【讨论】:

  • 函数window.history.pushState是对象window.history的子/方法。只测试功能还不够吗?
  • 如果浏览器没有实现历史 API,@OliverSchafeld 测试 window.history.pushState (或首先)可能会抛出 Cannot read property 'pushState' of undefined。所以这两个测试是需要的,按照这个特定的顺序。
  • @Nico Prat :啊,当然,谢谢。测试像 !!window.history.madeupproperty 这样不存在的属性会产生 false。所以我猜if(!!window.history.pushState) 可能会。无法使用 IE9 (caniuse.com/#feat=history) 进行正确测试。但只需检查!!window.notexistent.madeup 就会引发“无法读取属性...”错误。所以if (window.history && window.history.pushState) 是真正需要的,而且也是按这个顺序。
  • 在 Chrome、FF 和 IE11 中为我工作
  • 非常有用的代码,但是,正如@Portekoi 指出的那样,不要阻止两次后退按钮。为了实现完全阻塞功能,我在alert('...') 行之后添加了最后一行window.history.pushState('forward', null, './#forward')。这成功了...没有刷新或对后退按钮单击有任何明显影响。
【解决方案3】:

我知道的最好方法

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

【讨论】:

  • 这在 chrome 中不起作用。
  • 这不会禁用后退按钮,因为它会阻止任何浏览(后退、前进、刷新),并允许用户使用超出的提示停止它您的控制权。
  • 这将禁用导航离开页面 - 包括关闭页面、返回和前进,并且不回答问题。
【解决方案4】:

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

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.
    };
}

它可以工作,但我必须在 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);  
    }
};

}

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

有人知道我可以修复它吗?

【讨论】:

    【解决方案5】:

    由于后退按钮是浏览器的一项功能,因此很难更改默认功能。虽然有一些解决方法。看看这篇文章:

    http://www.irt.org/script/311.htm

    通常,需要禁用后退按钮是编程问题/缺陷的良好指标。我会寻找一种替代方法,例如设置会话变量或存储表单是否已提交的 cookie。

    【讨论】:

    • 如果你做任何远程现代的事情,后退按钮的默认操作是不合适的。这是因为后退按钮是 ajax 之前网络不切实际的一种解决方法。
    【解决方案6】:

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

    以下是一些可能的解决方案: JQuery History Salajax A Better Ajax Back Button

    【讨论】:

    • 不,实际上我有一个表单,提交表单后我将用户重定向到另一个页面。所以,这里我不想让用户点击后退按钮并转到表单页面。
    • @ibh:Post/Redirect/Get (PRG) pattern 可能适合您的需求。
    • 如果您只是让他们进入页面,但在单击按钮时设置一个变量(或会话或 cookie),告诉应用程序不要显示任何表单,这不是更容易吗更多的?您可以简单地隐藏表单并提供另一个“感谢您已经填写表单页面”或者,如果已设置该变量,则自动重定向。这也会阻止他们以最初的方式导航。
    • @ibh:或者使用 Ajax 发送表单(使用普通的非 JavaScript 回退),这样您就可以让表单在成功后消失,而无需在浏览器历史记录中添加新页面。跨度>
    猜你喜欢
    • 2013-07-09
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 2013-08-11
    相关资源
    最近更新 更多