【问题标题】:JavaScript or jQuery browser back button click detectorJavaScript 或 jQuery 浏览器后退按钮点击检测器
【发布时间】:2013-07-09 18:51:54
【问题描述】:

有人可以分享我们如何检测浏览器后退按钮点击的经验/代码吗(适用于任何类型的浏览器)?

我们需要满足所有不支持 HTML5 的浏览器

【问题讨论】:

标签: javascript jquery back-button


【解决方案1】:

“popstate”事件仅在您之前推送某些内容时有效。所以你必须这样做:

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

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

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

    $(window).on('popstate', function() {
      alert('Back button was pressed.');
    });

  }
});

为了浏览器向后兼容性,我推荐:history.js

【讨论】:

  • 这个不区分后退或前进按钮,只是popstate,两者都可以
  • 您的代码在桌面浏览器中运行良好,但在移动浏览器中无法正常运行
  • 但是对 backword 和 forward 都发出警报,我怎样才能只检测到 back click
  • "'popstate' 事件仅在您之前推送某些内容时有效。"这是黄金!有很多例子,但最重要的是这个准确的引用!
  • 代码原样只对给定页面有效。如果添加另一个“window.history.pushState('forward', null, './#forward');”警报后,它一直阻止用户使用后退按钮....呵呵
【解决方案2】:

在 javascript 中,导航类型 2 表示单击了浏览器的后退或前进按钮,并且浏览器实际上正在从缓存中获取内容。

if(performance.navigation.type == 2) {
    //Do your code here
}

【讨论】:

  • 除非页眉包含“no-store”或“must-revalidate”
  • 这不再有效。 perfermance.navigation.type 只给出一个值 0 并且已被弃用,并且并非所有浏览器都支持它的替代方案。
  • 谢谢哈桑,它成功了,这正是我想要的。
【解决方案3】:

有很多方法可以检测用户是否单击了“返回”按钮。但是一切都取决于您的需求。尝试浏览下面的链接,它们应该会对您有所帮助。

检测用户是否按下当前页面上的“返回”按钮:

在上一个(“前进”)页面上按“返回”按钮后检测当前页面是否被访问:

【讨论】:

    【解决方案4】:

    发现它可以很好地跨浏览器和移动设备back_button_override.js

    (为 safari 5.0 添加了一个计时器)

    // managage back button click (and backspace)
    var count = 0; // needed for safari
    window.onload = function () { 
        if (typeof history.pushState === "function") { 
            history.pushState("back", null, null);          
            window.onpopstate = function () { 
                history.pushState('back', null, null);              
                if(count == 1){window.location = 'your url';}
             }; 
         }
     }  
    setTimeout(function(){count = 1;},200);
    

    【讨论】:

    • 在 Firefox 上就像一个魅力,但由于某种原因,它并不总是在 Chrome 上工作:/。有关如何改进它以在 Chrome 上运行的任何建议?
    【解决方案5】:

    在 HTML5 的情况下,这可以解决问题

    window.onpopstate = function() {
       alert("clicked back button");
    }; history.pushState({}, '');
    

    【讨论】:

      【解决方案6】:

      你可以使用这个很棒的插件

      https://github.com/ianrogren/jquery-backDetect

      你需要做的就是写这段代码

        $(window).load(function(){
          $('body').backDetect(function(){
            // Callback function
            alert("Look forward to the future, not the past!");
          });
        });
      

      最好的

      【讨论】:

        【解决方案7】:

        在我的例子中,我使用 jQuery .load() 来更新 SPA (single page [web] app) 中的 DIV。

        刚开始使用 $(window).on('hashchange', ..) 事件侦听器,这被证明具有挑战性,并且需要一些时间来破解。由于阅读了很多答案并尝试了不同的变化,终于弄清楚了如何使其以下列方式工作。据我所知,到目前为止它看起来很稳定。

        总而言之 - 每次加载视图时都应设置变量 globalCurrentHash

        然后当$(window).on('hashchange', ..) 事件监听器运行时,它会检查以下内容:

        • 如果location.hash 的值相同,则表示前进
        • 如果location.hash 的值不同,则表示返回

        我意识到使用全局变量并不是最优雅的解决方案,但是到目前为止,在 JS 中做面向对象的事情对我来说似乎很棘手。改进/改进的建议当然值得赞赏


        设置:

        1. 定义一个全局变量:
            var globalCurrentHash = null;
        
        1. 调用.load() 更新DIV 时,也要更新全局变量:

          function loadMenuSelection(hrefVal) {
            $('#layout_main').load(nextView);
            globalCurrentHash = hrefVal;
          }
          
        2. 在页面准备就绪时,设置监听器以检查全局变量以查看是否按下了返回按钮:

          $(document).ready(function(){
            $(window).on('hashchange', function(){
                console.log( 'location.hash: ' + location.hash );
                console.log( 'globalCurrentHash: ' + globalCurrentHash );
          
                if (location.hash == globalCurrentHash) {
                    console.log( 'Going fwd' );
                }
                else {
          
                    console.log( 'Going Back' );
                    loadMenuSelection(location.hash);
                }
              });
          
          });
          

        【讨论】:

          【解决方案8】:

          它在 HTML5 History API 中可用。该事件被称为'popstate'

          【讨论】:

          • 我们需要满足所有不支持 HTML5 的浏览器
          【解决方案9】:

          通过以下功能禁用url按钮

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

          【讨论】:

            【解决方案10】:

            Hasan Badshahanswer 为我工作,但该方法将被弃用,并且可能对其他人造成问题。遵循 MDN 网络文档关于替代方法,我登陆这里:PerformanceNavigationTiming.type

            if (performance.getEntriesByType("navigation")[0].type === 'back_forward') {
              // back or forward button functionality
            }
            

            这并不能直接解决后退按钮而不是前进按钮的问题,但足以满足我的需要。在文档中,他们详细介绍了可能有助于解决您的特定需求的可用事件数据:

            function print_nav_timing_data() {
              // Use getEntriesByType() to just get the "navigation" events
              var perfEntries = performance.getEntriesByType("navigation");
            
              for (var i=0; i < perfEntries.length; i++) {
                console.log("= Navigation entry[" + i + "]");
                var p = perfEntries[i];
                // dom Properties
                console.log("DOM content loaded = " + (p.domContentLoadedEventEnd - 
                p.domContentLoadedEventStart));
                console.log("DOM complete = " + p.domComplete);
                console.log("DOM interactive = " + p.interactive);
            
                // document load and unload time
                console.log("document load = " + (p.loadEventEnd - p.loadEventStart));
                console.log("document unload = " + (p.unloadEventEnd - 
                p.unloadEventStart));
            
                // other properties
                console.log("type = " + p.type);
                console.log("redirectCount = " + p.redirectCount);
              }
            }
            

            根据本文发布时的文档,它仍处于工作草案状态,不支持 IE 或 Safari,但在完成时可能会发生变化。检查文档以获取更新。

            【讨论】:

              【解决方案11】:

              假设你有一个按钮:

              <button onclick="backBtn();">Back...</button>
              

              这里是backBtn方法的代码:

                function backBtn(){
                                  parent.history.back();
                                  return false;
                              }
              

              【讨论】:

              • 我不明白为什么@senior 投票失败??这确实有效!如果有什么我应该知道的,请告诉我。 ..
              • @Ingus 可能是因为这与浏览器本身的后退导航按钮无关。这是为了在您的页面上创建自定义后退按钮。
              • 这不是返回按钮。
              猜你喜欢
              • 2016-10-29
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-09-15
              • 2011-12-26
              • 2014-11-06
              相关资源
              最近更新 更多