禁用特定url的浏览器后退按钮

Disabling browser back button for specific url

本文关键字:浏览器 按钮 url      更新时间:2023-12-01

我想禁用浏览器返回按钮,或者说不想让用户从特定的url导航回来。假设url是:

http://localhost/emptracker/#setup

所以我想要的是,当用户来到这个网址时,后退按钮应该被禁用。目前,我阅读了许多Stack Overflow的帖子,并尝试了类似的解决方案

<script type="text/javascript">
    history.pushState(null, null, 'pagename');
    window.addEventListener('popstate', function(event) {
        history.pushState(null, null, 'pagename');
    });
</script>

但问题是,它禁用了整个应用程序中url的后退按钮,我想对特定的url执行此操作。我的应用程序是基于backbonej的。

使用它。我认为这对你有帮助

file1.html:

<form action="page2.html#no-back" method="post" />
  <input type="text" name="data" value="The data" />
  <input type="submit" value="Send data" />
</form>

file2.html

// It works without the History API, but will clutter up the history
var history_api = typeof history.pushState !== 'undefined'
// The previous page asks that it not be returned to
if ( location.hash == '#no-back' ) {
  // Push "#no-back" onto the history, making it the most recent "page"
  if ( history_api ) history.pushState(null, '', '#stay')
  else location.hash = '#stay'
  // When the back button is pressed, it will harmlessly change the url
  // hash from "#stay" to "#no-back", which triggers this function
  window.onhashchange = function() {
    // User tried to go back; warn user, rinse and repeat
    if ( location.hash == '#no-back' ) {
      alert("You shall not pass!")
      if ( history_api ) history.pushState(null, '', '#stay')
      else location.hash = '#stay'
    }
  }
}

访问本文工作文件

通过在线演示访问本文