Disable browser back button for one page application

Developer107 picture Developer107 · Jul 9, 2015 · Viewed 26.7k times · Source

I need to disable the back button of browser in my single page application. I tried using methods like onhashchange or window.history.forward but they don't work (reason may be that url doesn't get changed here)

Answer

relizondo6 picture relizondo6 · Jul 17, 2015

I work in AngularJS building a Single Page App and I wanted to disable or prevent the back button of the browser, because my app has buttons and anchors for all navegation into my app.

I searched and test many codes, and this is the easy to prevent the back button of browsers and the following code worked for me.

window.onpopstate = function (e) { window.history.forward(1); }

When the history detects the first history.back()

window.onpopstate

is executed, then after this moment any back or forward in history are detected for onpopstate event.