Disable browser back button for one page application
I dont think disabling the back button will really work. So many reasons for same but have look at this. Your best solution will be warn the user using
window.onbeforeunload = function() { return "You will leave this page"; };
import { LocationStrategy } from '@angular/common';
constructor( private location: LocationStrategy){
// preventing back button in browser implemented by "Samba Siva"
history.pushState(null, null, window.location.href);
this.location.onPopState(() => {
history.pushState(null, null, window.location.href);
});
}
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.