Prevent Browser Back and Forward Button using JQuery

In this blog, am going to explain how we can prevent the browser back and forward button. Sometimes, for security reasons, once the user has logged out of the application, we generally clear all the sessions, we also make sure that the user is not able to navigate to the previous or page.

Let’s say there are two forms, default1.aspx and default2.aspx, and we need to prevent the user to navigate back to the default1.aspx once the user is in the default2.aspx.

This code, tested in IE, Chrome and Firefox

Prevents Back button default1.aspx

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
script type = "text/javascript" >
window.history.forward();

function
preventBack() { window.history.forward(1); }
//setTimeout("preventBack()", 0);

//window.onunload = function () { null };
</script>
<
title>
</
title>
</
head>
<
body onload="preventBack();" onpageshow="if (event.persisted) preventBack();" onunload="">
<
form id="form1" runat="server">
<
div>
</
div>
</
form>
</
body>
</
html>

Default2.aspx

<!DOCTYPE html>
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title></title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:HyperLink ID="HyperLink1" NavigateUrl="~/Default.aspx" runat="server">Go back </asp:HyperLink>
</
div>
</
form>
</
body>
</
html>

Now, if you are in the default2.apsx and want to go to the default1.aspx by clicking on the browser back button, the code will not allow the user to navigate to default1.aspx., you can navigate to default1.aspx only by clicking on the “Go back” link.

Ebook Download
View all
Learn
View all