Search code examples
javascriptjquerybuttonbrowserback

Disable browser back button for one page application


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)


Solution

  • 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.