Note:
- This code was tested and worked fine, without any problems, however I would encourage developers to test it again before starting to work with the code.
- If HTML5 history.replaceState () is used somewhere in your application, the code below may now work.
I created a custom function to disable the forward button.
Here is the code (it does not work with the hash routing strategy):
<script> (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 && 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 noted in the comments on the accepted answer, the problem is that you need to double-click the "Back" button to return to the page, which is tedious and impractical.
Code Explanation: Each time you press the back button, you need to create an additional history element so that the current page you are on points to a newly created history page. Thus, there is no page to go forward because pushState
is the last state (imagine it as the last element in the array), so your forward button will always be disabled.
The reason you had to enter a loop variable is because you might have a script where you go back to a specific page and pushState
code appears that creates the last element of the story, and instead, going back, you select the click for some, follow the link back to the previous page, which now creates an additional element of the story. In other words, you have something like this:
[page1, page2, page2, page2]
Now, when you turn on page2
(index 3 element) and press the back button again, you will again get index 1 element on page2
, and you donβt need it. Remember that you may have an array of x
page2
elements, therefore, to resolve this particular case, a false loop variable was introduced, with which you go from page2
to page 1 no matter how many page2
elements page2
are in the array.