Disable browser forward button in JavaScript

I’ve been trying to find some code recently to disable the forward button in the browser. Unfortunately, there has been no success with googling thereby I had to create a custom function to execute after the web-page has finished with content loading.

For those who are uninterested why this whole bunch of code had to be written and how the “button navigation disabling” actually works, just copy and paste the code into your app. The code had been tested in a manner of clicking and navigating back on a custom application, however, I urge you to test it extensively before going to production with it.

There are however 3 things which should be considered:

  • it won’t work on IE<10
  • it wont’ work using a hashlocation strategy (popular in react and angular frameworks)
  • if HTML5 history.replaceState() is used anywhere in your application then the code below might not work because of the replaceState canceling pushState() behaviour in the below code.

function for disabling the forward navigation button:


(function() {
  // function called after the DOM has loaded
  disableForwardButton();
})();

function disableForwardButton() {
  var flag, loop = false;
  window.addEventListener('popstate', function(event) {
    if (flag) {
      if (history.state != null && 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;
  };
}

Code Explanation:

In order to appropriately tackle the problem you first have to understand what is at your disposal and how these tools/commands work inside back navigation event (‘popstate’).

We’ll be using the following code:

  • history.go(-1), history.back() –> navigate backwards
    history.pushState(arg1, arg2, arg3) –> adding an extra entry element to our browser navigation array
  • ‘popstate’ event –> catches back, forward navigation click
    ‘onclick’ event –> catches any click event on the window object (needed to reset variables if the ‘popstate’ event occurred)

First, have in mind that there isn’t a switch off JavaScript code which would disable either the navigation forward button or the backwards button, therefore you have to take another approach which would prevent the app-user to click on the forward button.

The crucial thing to use here is the history.pushState() HTML 5 history API. Basically what it does (once used) is putting your current page at the end of the browser navigation array. In other words, if you execute this code in the ‘popstate’ event it would create another history and push it to the end of the array therefore disallowing the click of the forward button since you are on the last position (last item of the array). By doing this you haven’t disabled it at all you just appended an item to the array. Since you are now located at the end of the array then obviously you cannot go further (click forward).

To illustrate it a little bit more let’s create array states before the implementation of the pushState and after its implementation.

We’ll be using the following presumption of page history [page1, page2, page3]

  1.  let the current page we are on be page3. Once someone clicks the back button the ‘popstate’ event listener catches the event action and moves to page2
  2. Now again, let the current page be page3. With the pushState() function being implemented inside our ‘popstate’ listener the following transformation will occur inside our array [page1, page2, page2]. The page3 has been removed from the history and once landing on page 2 we pushed that exact page once more in the array and from that we’ve got no where else to go, our array doesn’t permit us to navigate forward like it did in the previous example. Because of the “no where going” the forward button in the browser is disabled or better to say inactive.

Once pushState() is implemented in our ‘popstate’ event we can now use the history.go(-1) function which helps us navigate to our previous page. The reason why we need it, is because pushState() will constantly push states (populate our browser page history) like the method name indicates therefore we will once be able to navigate back and after hitting the back button again we’ll be stuck on the current page. In order to evade this scenario we have to trigger a second back button click by using history.go(-1) or history.back(). The history.go(-1) will again trigger an event as we hit the back button and go through our code inside the popstate eventlistener. As you can see, we toggle between the history.go(-1) and pushState() in order to keep our forward button disabled and being able to navigate back.

The last thing which needs clarification is the code below:

if (history.state != null && history.state.hasOwnProperty('page')) {
  loop = true;
  history.go(-1);
}

Without this peace of code the forward button disabling would still work but you could run to a “never ending” back button navigation. This means that if you navigated back and have appended a vast number of elements inside your browser navigation array like for instance

[page0, page1, page2, page2, page2, page2, page2]

you would have to click the button numerous times in order to navigate to page1. Of-course, no one wants that, but such situation is very plausible and occurs often (the accumulation of pages in the array).

It happens because you might stop back navigating at some point (remember, pushState function executes at every back navigation button click) then click on some url within the webpage and then again navigate back going through page2 all the way to the starting page for example. Let’s say that you create this precise scenario:

[page0, page1, page2, page2, page2, page2, page2]

Having a bunch of same pages in the array and wanting to just jump to the target page which is page0. In this case we need to execute history.go(-1) until we reach the page1 (we cannot magically jump to it, we need to go through each and every element that we’ve created unwantedly) and then stop. this is done by setting the loop variable to true so that we don’t pushState() until we reach page1 where we pushState() again to disable the forward button.

That’s basically it. The HTML5 history API doesn’t allow you to explicitly look at their navigational array because of that we need to implement this dirty code to have our forward button disabled for the entire application.

If you notice a bug or have some uncertainties on how to implement the code, feel free to contact me.

Link to my stackoverflow answer