Skip to content Skip to sidebar Skip to footer

Html5 History Disabling Forward Button

I am writing a single page javascript application using the HTML5 History API. The application loads content via Ajax and internally maintains state information on the foreground s

Solution 1:

Bad Part

To really disable the forward button, you would have to be able to delete browser history, which is not allowed by all javascript implementations because it would allow sites to delete the entire history, which would never be in the interest of the user.

Good Part

This is a bit tricky, but I guess it could work if you want to do custom history. You could just use pushState in the popstate event to make your actual page the topmost history entry. I assume the way you handle your history, your window will never unload. This allows you to keep track of the user history yourself:

var customHistory = [];

Push every page you load with history.pushState(screenData, window.document.title, "#");, like you did before. Only you add the state to your custom history, too:

history.pushState(screenData, window.document.title, "#");
customHistory.push({data: screenData, title: window.document.title, location: '#'});

now if you have a popstate event, you just pop you custom history and push it to the topmost entry:

window.onpopstate = function(e) { 
  var lastEntry = customHistory.pop();
  history.pushState(lastEntry.data, lastEntry.title, lastEntry.location);
  // load the last entry
}

Or in jQuery

$(window).on('popstate', function(e) {
  var lastEntry = customHistory.pop();
  history.pushState(lastEntry.data, lastEntry.title, lastEntry.location);
  // load the last entry
});

Solution 2:

The accepted answer solves the problem to disable the forward button, but creates a new annoying issue "the page navigated back to" is inserted in duplicate into the history (as indicated in the answers comments).

Here is how solve the question "diabled forward button" and to avoid the "duplicate" back-button-issue.

//setup the popstate EventListener that reacts to browser history events
window.addEventListener("popstate",function(event){
     // In order to remove any "forward"-history (i.e. disable forward // button), this popstate's event history state (having been navigated // back to) must be insert _again_ as a new history state, thereby // making it the new most forwad history state. // This leaves the problem that to have this popstate event's history// state to become the new top, it would now be multiple in the history//// Effectively history would be://  * [states before..] ->//  * [popstate's event.state] -> //  * [*newly pushed _duplicate_ of popstate's event.state ]// // To remove the annoyance/confusion for the user to have duplicate// history states, meaning it has to be clicked at least twice to go // back, we pursue the strategy of marking the current history state// as "obsolete", as it has been inserted _again_ as to be the most// forward history entry. // // the popstate EventListener will hence have to distinguish 2 cases://// case A) "popstate event is _not_ an obsolete duplicate"...if( typeofevent.state == "object" 
         && event.state.obsolete !== true)
     {
         //...so we _firstly_ mark this state as to from now on "obsolete",// which can be done using the history API's replaceState method
         history.replaceState({"obsolete":true},"");
         // and _secondly_ push this state _one_more_time_ to the history// which will solve the OP's desired "disable forward button" issue
         history.pushState(event.state,"");
     }

     // case B: there is the other case that the user clicked "back" and// encounters one of the duplicate history event entries that are // "obsolete" now.if( typeofevent.state == "object" 
         && event.state.obsolete === true)
     {
         //...in which case we simply go "back" once more 
         history.back() 
         // by this resolving the issue/problem that the user would// be counter-intuively needing to click back multiple times.// > we skip over the obsolete duplicates, that have been the// the result of necessarily pushing a history state to "disable// forward navigation"
     }

},false);

Solution 3:

Just use following jquery to disable forward button:

  $( document ).ready( function(){
    history.pushState(null,  document.title, location.href);        
   });

Solution 4:

NOTE:

  • This code was tested and worked fine without showing any problems, however I would incentivize developers to test it more before going to production with the code.
  • If HTML5 history.replaceState() is used anywhere in your application, the code below might now work.

I created a custom function in order to disable the forward button.

Here is the code (it doesn't work with the hash routing strategy):

<script>
    (function() {
      // function called after the DOM has loadeddisableForwardButton();
    })();

    functiondisableForwardButton() {
      var flag, loop = false;
      window.addEventListener('popstate', function(event) {
        if (flag) {
          if (history.state && history.state.hasOwnProperty('page')) {
            loop = true;
            history.go(-1);
          } else {
            loop = false;
            history.go(-1);
          }
        } else {
          history.pushState({
              page: true
            },
            null,
            null
          );
        }
        flag = loop ? true : !flag;
      });

      window.onclick = function(event) {
        flag = false;
      };
    }
  </script>

As Redrif pointed out in the comments of the accepted answer, the problem is that you have to double click the back button in order to navigate back to the page which is tedious and impractical.

Code explanation: each time you click the back button you need to create an additional history element so that the the current page which you are located on points to the newly created history page. In that way there is no page to go forward to since the pushState is the last state (picture it as the last element in the array) therefore your forward button will always be disabled.

The reason why it was mandatory to introduce the loop variable is because you can have a scenario where you go back to a certain page and the pushState code occurs which creates the last history element and instead going back again you choose to click on some link again and again go back the previous page which now creates an additional history element. In other words, you have something like this:

[page1, page2, page2, page2]

now, once on page2 (index 3 element) and you click the back button again you will get to the page2 again index 1 element and you do not want that. Remember that you can have an array of xpage2 elements hence the loop false variable was introduced to resolve that particular case, with it you jump all the way from page2 to page 1 no matter how many page2 elements are their in the array.

Post a Comment for "Html5 History Disabling Forward Button"