Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to disable browser's back button with JavaScript?
To disable the browser's back button, you can use JavaScript's history.forward() method to prevent users from navigating backward. This technique forces the browser to stay on the current page when the back button is clicked.
Basic Approach
The core idea is to push the current page forward in history whenever the user tries to go back:
<html>
<head>
<title>Disable Browser Back Button</title>
</head>
<body>
<h1>Main Page</h1>
<a href="newpage.html">Next Page</a>
<script>
function disableBack() {
window.history.forward();
}
// Disable back when page loads
window.onload = disableBack;
// Handle page show event for cached pages
window.onpageshow = function(evt) {
if (evt.persisted) disableBack();
}
</script>
</body>
</html>
Example: Complete Implementation
Here's a working example with both pages:
<!-- index.html -->
<html>
<head>
<title>Page 1 - Back Button Disabled</title>
</head>
<body>
<h1>Page 1</h1>
<p>Click the link to go to the next page. The back button will be disabled.</p>
<a href="page2.html">Go to Page 2</a>
<script>
// Prevent going back to previous page
history.pushState(null, null, location.href);
window.onpopstate = function() {
history.go(1);
};
</script>
</body>
</html>
<!-- page2.html -->
<html>
<head>
<title>Page 2 - Back Button Disabled</title>
</head>
<body>
<h1>Page 2</h1>
<p>Try using the browser's back button - it won't work!</p>
<script>
// Alternative method using history.forward()
function disableBack() {
window.history.forward();
}
window.onload = disableBack;
window.onpageshow = function(evt) {
if (evt.persisted) disableBack();
}
</script>
</body>
</html>
How It Works
The technique works by:
- history.forward() - Moves the browser forward in history
- onpageshow event - Handles cached pages that might bypass onload
- evt.persisted - Detects if page was loaded from browser cache
Alternative Method Using popstate
<script>
// Push current state to history
history.pushState(null, null, location.href);
// Intercept back button clicks
window.onpopstate = function() {
history.go(1); // Go forward instead of back
};
</script>
Important Considerations
Note: Disabling the back button can create poor user experience and may not work in all browsers or scenarios. Modern browsers provide limited control over navigation for security reasons.
| Method | Reliability | User Experience |
|---|---|---|
history.forward() |
Moderate | Can be confusing |
onpopstate |
Better | More seamless |
Conclusion
While you can disable the back button using JavaScript history manipulation, consider the user experience impact. Use this technique sparingly and only when absolutely necessary for security or workflow reasons.
