In this article I will explain with an example, how to prevent user from navigate to previous page using
Back Button in Browser or the Back option in the Context Menu using
AngularJS.
One cannot disable the Browser Back Button functionality only thing that can be done is prevent them going back.
Disabling Browser Back Button using AngularJS
Login Page
The HTML Markup of Login page consists of following element:
div - For applying
ng-app and
ng-controller AngularJS directives.
The HTML Markup also consists of an HTML Anchor tag and its href property is set to name of Home page.
Inside the HTML Markup, first the following script file is inherited.
1. angular.min.js
Inside the
AngularJS Controller, the
timeout function is called which schedules the execution time with delay of 0 (zero) milliseconds.
Inside the timeout function, the $window.history.forward() method is called which navigates the browser forward one step in their history. Whenever Browser Back Button is clicked, this function immediately moves it one step forward.
Finally, the unload event handler is attached to the window using addEventListener method which returns NULL to disable (prevent) the Browser Back Button.
<html>
<head>
<title>Login</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("MyApp", []);
app.controller("MyController", function ($scope, $window, $timeout) {
$timeout(function () {
$window.history.forward();
}, 0);
$window.addEventListener('unload', function () {
null;
});
});
</script>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<h3>Login</h3>
<hr />
<a href="Home.htm">Redirect to Home</a>
</div>
</body>
</html>
Home Page
The HTML Markup of Home page consists of following element:
div - For applying
ng-app and
ng-controller AngularJS directives.
The HTML Markup of Home page also consists of an HTML Anchor tag and its href property of the Anchor link is set to name of Login page.
Note: HTML Anchor link is added to illustrate that the Login page will be prevented only using Browser Back Button and not when accessed using other means.
Inside the HTML Markup, first the following script file is inherited.
1. angular.min.js
The
AngularJS Controller left empty as it is not required.
<html>
<head>
<title>Home</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("MyApp", []);
app.controller("MyController", function ($scope, $window) { });
</script>
</head>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<h3>Home</h3>
<hr />
<a href="Login.htm">Redirect to Login</a>
</div>
</body>
</html>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads