您如何确定地检测用户是否在浏览器中按下了后退按钮?

如何使用#URL系统在单页web应用程序中强制使用页面内返回按钮?

为什么浏览器的后退按钮不触发它们自己的事件!?


当前回答

我能够使用这篇文章中的一些答案和其他人让它在IE和Chrome/Edge中工作。历史。IE11中不支持pushState。

if (history.pushState) {
    //Chrome and modern browsers
    history.pushState(null, document.title, location.href);
    window.addEventListener('popstate', function (event) {
        history.pushState(null, document.title, location.href);
    });
}
else {
    //IE
    history.forward();
}

其他回答

我已经为这个需求挣扎了很长一段时间,并采用了上面的一些解决方案来实现它。然而,我偶然发现,它似乎可以在Chrome、Firefox和Safari浏览器以及Android和iPhone上运行

页面加载:

window.history.pushState({page: 1}, "", "");

window.onpopstate = function(event) {

  // "event" object seems to contain value only when the back button is clicked
  // and if the pop state event fires due to clicks on a button
  // or a link it comes up as "undefined" 

  if(event){
    // Code to handle back button or prevent from navigation
  }
  else{
    // Continue user action through link or button
  }
}

如果有帮助请告诉我。如果我错过了什么,我会很高兴去理解。

我能够使用这篇文章中的一些答案和其他人让它在IE和Chrome/Edge中工作。历史。IE11中不支持pushState。

if (history.pushState) {
    //Chrome and modern browsers
    history.pushState(null, document.title, location.href);
    window.addEventListener('popstate', function (event) {
        history.pushState(null, document.title, location.href);
    });
}
else {
    //IE
    history.forward();
}

浏览器:https://jsfiddle.net/Limitlessisa/axt1Lqoz/

移动控制:https://jsfiddle.net/Limitlessisa/axt1Lqoz/show/

$(document).ready(function() { $('body').on('click touch', '#share', function(e) { $('.share').fadeIn(); }); }); // geri butonunu yakalama window.onhashchange = function(e) { var oldURL = e.oldURL.split('#')[1]; var newURL = e.newURL.split('#')[1]; if (oldURL == 'share') { $('.share').fadeOut(); e.preventDefault(); return false; } //console.log('old:'+oldURL+' new:'+newURL); } .share{position:fixed; display:none; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,.8); color:white; padding:20px; <!DOCTYPE html> <html> <head> <title>Back Button Example</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body style="text-align:center; padding:0;"> <a href="#share" id="share">Share</a> <div class="share" style=""> <h1>Test Page</h1> <p> Back button press please for control.</p> </div> </body> </html>

看到这个:

history.pushState(null, null, location.href);
    window.onpopstate = function () {
        history.go(1);
    };

它工作得很好……

我尝试了上面的方法,但是没有一个对我有效。这是解决方案

if(window.event)
   {
        if(window.event.clientX < 40 && window.event.clientY < 0)
        {
            alert("Browser back button is clicked...");
        }
        else
        {
            alert("Browser refresh button is clicked...");
        }
    }

详情请参考http://www.codeproject.com/Articles/696526/Solution-to-Browser-Back-Button-Click-Event-Handli