• By :  Piyush Rishi Singh
  • Last Updated :  December 2, 2022
  • Words Count :  378 Words
  • Est. Reading Time :  3 mins

Sometimes we have requirement in developing a website to disable the Back button effect from Browser. This is common in Online Banking Websites and other sites where security is of principal concern. User may hit back and navigate from the page and forget to logout.

Hence sometime it is required that we disable the functionality of Back button. But unfortunately this is not an easy task. There is no direct way of dealing with this problem. We can do few hacks to ensure that user does not get back in the browser.

Following trick can be used to disable the back button in browser. Please note that we do not literally “disable” the back button, but just nullify its effect is some case and hide it altogether in others.

Disable Back functionality using history.forward

This is another technique to disable the back functionality in any webpage. We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following code in page1.

<SCRIPT type="text/javascript">
	window.history.forward();
	function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();" 
	onpageshow="if (event.persisted) noBack();" onunload="">

The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.

Warn User if Back is Pressed

You may want to warn user if Back button is pressed. This works in most of the cases. If you have some unsaved form data, you might want to trigger a warning message to user if Back button is pressed.

Following Javascript snippet will add a warning message in case Back button is pressed:

window.onbeforeunload = function() { return "You work will be lost."; };

Include this in your HTML page to popup a warning message.

Share :
Piyush Rishi Singh

Piyush Rishi Singh

www.piyushrishisingh.com
(Founder & Business Head At Techzax Innovations Pvt. Ltd.)

A Digital Entrepreneur & Content Creator who loves simplifying tech.
Expertise: A Full Stack & highly skilled 10+ years experienced WordPress developer who specializes in complete custom tailored WordPress Websites development.

Table Of Contents