简体   繁体   English

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

[英]JavaScript or jQuery browser back button click detector

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 的浏览器

The 'popstate' event only works when you push something before. 'popstate' 事件仅在您之前推送某些内容时有效。 So you have to do something like this:所以你必须做这样的事情:

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

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
}

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:在上一页(“前进”)按“后退”按钮后检测当前页面是否被访问:

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

In case of HTML5 this will do the trick在 HTML5 的情况下,这将解决问题

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

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最好的

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. $(window).on('hashchange', ..)开始使用$(window).on('hashchange', ..)事件侦听器,这个被证明具有挑战性并且需要一些破解。 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.据我所知,到目前为止它看起来很稳定。

In summary - there is the variable globalCurrentHash that should be set each time you load a view.总之 - 每次加载视图时都应该设置变量globalCurrentHash

Then when $(window).on('hashchange', ..) event listener runs, it checks the following:然后当$(window).on('hashchange', ..)事件侦听器运行时,它会检查以下内容:

  • If location.hash has the same value, it means Going Forward如果location.hash具有相同的值,则表示前进
  • If location.hash has different value, it means Going Back如果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.我意识到使用全局变量并不是最优雅的解决方案,但到目前为止,在 JS 中做面向对象的事情对我来说似乎很棘手。 Suggestions for improvement/refinement certainly appreciated改进/改进的建议当然值得赞赏


Set Up:设置:

  1. Define a global var :定义一个全局变量:
    var globalCurrentHash = null;
  1. When calling .load() to update the DIV, update the global var as well :当调用.load()更新 DIV 时,也要更新全局变量:

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

It's available in the HTML5 History API.它在 HTML5 History API 中可用。 The event is called 'popstate'该事件称为'popstate'

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

Hasan Badshah 's answer worked for me, but the method is slated to be deprecated and may be problematic for others going forward. Hasan Badshah回答对我有用,但该方法将被弃用,并且可能对其他人造成问题。 Following the MDN web docs on alternative methods, I landed here: PerformanceNavigationTiming.type遵循有关替代方法的 MDN 网络文档,我在这里登陆: PerformanceNavigationTiming.type

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

This doesn't directly solve for back button over the forward button, but was good enough for what I needed.这并不能直接解决前进按钮上的后退按钮,但足以满足我的需要。 In the docs they detail the available event data that may be helpful with solving your specific needs:在文档中,他们详细说明了可能有助于解决您的特定需求的可用事件数据:

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

According to the Docs at the time of this post it is still in a working draft state and is not supported in IE or Safari, but that may change by the time it is finished.根据本文发布时的文档,它仍处于工作草案状态,IE 或 Safari 不支持,但在完成时可能会发生变化。 Check the Docs for updates.检查文档以获取更新。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM