Search code examples
javascriptbrowser-history

Popping browser forward history using javascript


I'm working on a single page site and I want to use browser backward button to return to specified hash but I don't want user to be able to use forward button how can I disable it or pop all forwarding history stats?

In the code below code forward button won't cause any problem but I still want to disable it!

javascript:

var counter = 0;
var hashLocation = "page";
var selfChange = false;

function next() {
  selfChange = true;
  counter++;

  window.location.hash = "#" + hashLocation + counter;

  document.getElementById("container").innerHTML = window.location.hash.split("#")[1];
}

addEventListener('hashchange', (event) => {
  if (!selfChange) {
    document.getElementById("container").innerHTML = window.location.hash.split("#")[1];
  }
  selfChange = false;
});

html:

<a href="javascript: next();">add +</a>

<div id="container">

</div>

Solution

  • You can use history.pushState(null, document.title, window.location). When you use this, it will Clear forward history.