Announcement

Wednesday, 30 April 2014

How to prevent the functionality of browser back button?

Prevent the functionality of browser back button

In this post I will teach you how to prevent the functionality of browser back button.

Since, we have to prevent the back functionality of the browser, this can't be handled from the code-behind. This is the client functionality. So we need to so something at the client side.

So, we simply have to use javascript history object which is a part of the window object.

history object has 3 methods and 1 property.

history object methods:
  • forward()- loads the next URL in the history list. It won't work if the next page does not exist in the history list.
  • back()- loads the previous URL in the history list. It won't work if the previous page does not exist in the history list.
  • go()- loads the specific URL from the history list. It accepts either int parameter or string parameter.
history object property:
  • length- returns the number of URL in the history list.
I have created a javascript function where I have redirected the user to the current page using window.history.forward() method.


/*This is the function*/
function disableBackButton() {
window.history.forward()
}
/* call the function */
disableBackButton();

/* when the page loads again call the function */
window.onload=disableBackButton();

/* if the page is persisted than disable the back functionality */
window.onpageshow = function (evt) {
if (evt.persisted) disableBackButton()
}

/* do nothing on unload */
window.onunload = function () { void (0) }


NOTE: Place this code in the <script type=text/javascript></script> tag. The code should be placed on the page where the user see Log Out button.

No comments: