JavaScript 或 jQuery 浏览器后退按钮点击检测器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17594413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:22:36  来源:igfitidea点击:

JavaScript or jQuery browser back button click detector

javascriptjqueryback-button

提问by Nil Pun

Could someone please share experience / code how we can detect the browser back button click (for any type of browsers)?

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

We need to cater all browser that doesn't support HTML5

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

回答by Benny Neugebauer

The 'popstate' event only works when you push something before. So you have to do something like this:

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

  }
});

For browser backward compatibility I recommend: history.js

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

回答by Vlad Mysla

there are a lot of ways how you can detect if user has clicked on the Back button. But everything depends on what your needs. Try to explore links below, they should help you.

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

Detect if user pressed "Back" button on current page:

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

Detect if current page is visited after pressing "Back" button on previous("Forward") page:

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

回答by Hasan Badshah

In javascript, navigation type 2 means browser's back or forward button clicked and the browser is actually taking content from cache.

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

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

回答by user2992220

Found this to work well cross browser and mobile back_button_override.js .

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

(Added a timer for safari 5.0)

(为 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);

回答by Gene Bo

In my case I am using jQuery .load()to update DIVs in a SPA (single page [web] app).

就我而言,我使用 jQuery.load()更新 SPA (单页 [web] 应用程序)中的DIV 。

Being new to working with $(window).on('hashchange', ..)event listener , this one proved challenging and took a bit to hack on. Thanks to reading a lot of answers and trying different variations, finally figured out how to make it work in the following manner. Far as I can tell, it is looking stable so far.

作为使用$(window).on('hashchange', ..)事件侦听器的新手,这个被证明具有挑战性,并且需要一些技巧。由于阅读了大量答案并尝试了不同的变体,最终想出了如何使其以以下方式工作。据我所知,到目前为止它看起来很稳定。

In summary - there is the variable globalCurrentHashthat should be set each time you load a view.

Then when $(window).on('hashchange', ..)event listener runs, it checks the following:

  • If location.hashhas the same value, it means Going Forward
  • If location.hashhas different value, it means Going Back

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

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

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

I realize using global vars isn't the most elegant solution, but doing things OO in JS seems tricky to me so far. Suggestions for improvement/refinement certainly appreciated

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



Set Up:

设置:

  1. Define a global var :
  1. 定义一个全局变量:
    var globalCurrentHash = null;
  1. When calling .load()to update the DIV, update the global var as well :

    function loadMenuSelection(hrefVal) {
      $('#layout_main').load(nextView);
      globalCurrentHash = hrefVal;
    }
    
  2. On page ready, set up the listener to check the global var to see if Back Button is being pressed:

    $(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);
          }
        });
    
    });
    
  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);
          }
        });
    
    });
    

回答by Ashik Jyothi

In case of HTML5 this will do the trick

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

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

回答by Hussam Kurd

You can use this awesome plugin

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

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

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

All you need to do is to write this code

您需要做的就是编写此代码

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

Best

最好的事物

回答by Sakthi Karthik

Disable the url button by following function

通过以下功能禁用 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;
            }
        };
    }
};

回答by Eric

It's available in the HTML5 History API. The event is called 'popstate'

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

回答by senior

suppose you have a button:

假设你有一个按钮:

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

Here the code of the backBtn method:

这里是 backBtn 方法的代码:

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