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

时间:2015-02-17 05:32:53

标签: javascript jquery url browser frontend

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

http://localhost/emptracker/#setup

所以我想要的是当用户访问此URL时,后退按钮应该被禁用。现在我读了很多Stack Overflow帖子,并试过像这样的解决方案

<script type="text/javascript">

    history.pushState(null, null, 'pagename');

    window.addEventListener('popstate', function(event) {
        history.pushState(null, null, 'pagename');
    });

</script>

但问题是它禁用了应用程序中URL的后退按钮,我想为特定的URL做这个。我的应用程序基于backbonejs。

1 个答案:

答案 0 :(得分:0)

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

的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'
    }
  }
}

Visit This Article working File

OR

Visit this Article with online demo