Tuesday, 20 August 2013

Disable browser back button functionality using JavaScript in asp.net | ASP.Net disable browser back button (using javascript)

Categories: , , 
Introduction

Here I will explain how to disable browser back button functionality using JavaScript in asp.net.

Description

One day I got requirement like disable browser back button to prevent users going back to previous page using back button of the browser. I search many sites for proper code to prevent users navigating back to previous page but there is no use because some of them work in IE but not in Mozilla and some of them will work in Mozilla but not in IE.

Here this JavaScript functionality will work in all browsers and prevent users navigating back to previous page by hitting on browser back button check below piece of JavaScript code


<script type="text/javascript" language="javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
</script>
We need to place above script in header section of a page wherever we need to prevent users navigate back to another page by using browser back button. 

I will explain our requirement with an example I have two pages gupta1.aspx and gupta2.aspx now I will redirect from gupta1.aspx page to gupta2.aspx page. After come from gupta1.aspx page togupta2.aspx if I try to navigate back to gupta1.aspx page from gupta2.aspx then I want prevent user navigate back to previous page (gupta1.aspx). To achieve this functionality place above JavaScript function in header section of required page. 

After add our JavaScript functionality to our page that code will be like this


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Disable Browser Back buttons</title>
<script type="text/javascript" language="javascript">

function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
First Page
</div>
<div>
<asp:Button id="btnFirst" runat="server" Text="Go to First Page" PostBackUrl="~/Default.aspx"  />
<asp:Button ID="btnSecond" runat="server" Text="Go to Second Page" PostBackUrl="~/Default2.aspx" />
<asp:Button ID="btnThree" runat="server" Text="Go to Third Page" PostBackUrl="~/Default3.aspx" />
</div>
</form>
</body>
</html>

No comments:

Post a Comment