Explain Codes LogoExplain Codes Logo

How can I stop the browser back button using JavaScript?

javascript
prompt-engineering
callbacks
history-api
Nikita BarsukovbyNikita Barsukov·Dec 2, 2024
TLDR
// Preventing Back Button with a Stern Warning window.onbeforeunload = function() { return true; };

Caution: This action literally asks users whether they want to leave. Though efficient, it can be disruptive. User satisfaction comes first, so apply with moderation.

Steer user action with warnings

Adopt a stern parent's approach through UX considerations and thoughtful alerts. Picture your web page as a canvas filled with priceless data work. Alert users of potential data loss before they bid adieu or accidentally hit the iconic ⬅️:

// The stern parent script window.onbeforeunload = function(e) { e = e || window.event; // Old bros and IE need old school alerts if (e) { e.returnValue = 'Sure you want to leave? Your masterpiece might be lost!'; } // Cool kids get this return 'Sure you want to quit? Unsaving changes might bid adieu!'; };

Your web page won't decentralize browser controls or halt the back button operation but will at least make sure users take a momentary pause before leaving.

Full-on control: The History API

If you need to take matters into your own hands (for say, a single-page app), the History API is your knight in shining armor:

// Create initial history state: history.pushState({}, ''); // It's like the Big Bang but for a webpage // Back button clicks? We're listening window.onpopstate = function(event) { if(event.state){ // Handle their back-click energy, maybe redirect them? } else { // "Did you really think Back button works here? Cute :)" history.pushState({}, '', window.location.href); } };

With the power vested in this script, you're the puppeteer of user navigation!

Core functionality: Shield it

Remember, your creative solutions should not take a toll on any core functionality. So, the timers working overtime on your page should stay unaffected. And always be the champion of cross-browser compatibility. Thus, regular compatibility audits must be in your books.

Ethical and security check

Be aware, total control comes with a heavy conscience and a pinch of security uncertainty. Hence, it's discouraged to entirely disable the back button. Sometimes, a guiding light or a word of caution is all it takes to steer your user right.

Explore the roads less taken

Hash changes to hinder the back steps

Create a paradox for the browser by continuously resetting the window.location.hash.

// Buddy, you ain't going back! window.location.hash = 'no-back'; // Any hash changes? We hit refresh! window.onhashchange = function() { window.location.hash = 'no-back'; };

This forms a no-exit loop for the back button.

The breadcrumb trick

When your whole existence is about preventing back navigation (like, seriously?), provide the user with alternative means, say a breadcrumb navigation:

// I'm guiding you home, lost boy! // Breadcrumbs example: Home > Products > Checkout

Form Completion: Data Protection

In multi-step data input scenarios, you might want to preserve user data against back navigation. Consider using persistent localStorage or session-based sessionStorage to save data states

Ensure the back button handling does not break the navigation flow. Otherwise, it leaves users lost and leads to a poor UX.

Browser Compatibility

Ensure your methods support major browsers. Always refer to the compatibility resource, Can I Use, and the MDN Web Docs.