Sometimes we are in a situation that we don't want the user to visit the previous pages. This can be a scenario that users logs out but uses the back button to navigate to the pages. In this article I will tell you some simple ways you can use to prevent user from going back.

Preventing users to go back to the previous pages

Introduction:

Sometimes we are in a situation that we don't want the user to visit the previous pages. This can be a scenario when the user logs out but uses the back button to navigate to the pages. In this article I will show you some simple ways you can use to prevent user from going back.

Using History(+1) Method:

Let's say that you have a page called DemoPage.aspx which is the secure page and when you click the button you are redirected to another page FinalPage.aspx. Now from FinalPage.aspx you don't want to go back to the DemoPage.aspx. You can achieve this easily using few lines of code.

Let's first catch the button click event and send the user to the FinalPage.aspx page.

protected void Button1_Click(object sender, EventArgs e)

{

Response.Redirect("FinalPage.aspx");

}

Now if you press the button you will be redirected to the FinalPage.aspx page. If you press the back button you will be taken to the DemoPage.aspx page. Now we will implement the functionality that will prevent the user to go to the DemoPage.aspx page.

In the DemoPage.aspx html write the following code:

<body onLoad="if(history.length>0)history.go(+1)">

That's it. It means every time you will go to the DemoPage.aspx page you will be forwarded to the FinalPage.aspx.

Making a page with no toolbar:

Another solution is to make a page with no toolbar. No toolbar means that it will have no buttons, no navigation toolbar etc. In the Page_Load event of the DemoPage.aspx implement this code:

// Attach the event to the button click control

Button2.Attributes.Add("onclick", "CreateWindow()");

And now in the JavaScript code simply create the function CreateWindow which will open a new window and close the current window.

<script language =javascript>

function CreateWindow() {

window.open('SmallWindow.aspx','smallwindow','toolbar=false;target=_parent',true);

// just close the window and don't ask to close it

window.opener = self;

window.close();

}</script>

 

That's it. Now the new page SmallWindow.aspx will open without any toolbar hence you will not be able to go back.

I hope you liked the article, happy coding!