Tuesday, March 31, 2009

Handling Browser back button Issue in Java Script

If you were a web application developer you might have encountered a problem: "How the hell do I need to handle browser back button?" To your surprise if you do google search you wont get any useful information which helps you really to solve your problem. I worked on this type of problem along with my colleague and found one solution to these type of problems which I am going to share in my blog.

First let us discuss about the problem. Consider you have two pages (page1 and page2) where we can navigate page2 from page1. Let us assume that page2 will display a web form which has to be filled by the user and submit it to the server. Suppose if you have a requirement such that you need to warn the user whenver he click the back button when he is in page2 so that he may not loose any data he filled in the form. How do you think you can handle this?

There is no Javascript even which triggers when you click on the back button which will let your code know that a back button event has happened. The solution for this is using window.onbeforeunload event. From IE 4.0 Microsoft has introduced this event which can be used to control the browser history, keep track on back button click and so on. This event can help you to handle two things in your web page:
  • It will allow you to display a decision dialog box before the user leaves the current page
  • It will cause the browser to never do caching of the page

Eg. you can code like this

window.onbeforeunload = function() {
return "All your unsaved data will be lost"
}

This will display a decision box like
Are you sure you want to navigate from this page?
All your unsaved data will be lost
Click OK to continue, or Cancel to stay on the current page

You can notice that whatever string you placed in your return statement that string is wrapped up with two additional statements as shown above. So whenever a user clicks a back button this event is triggered and displays the above message and if he clicks on "OK" the page will navigate to prev page or else it should remain the same. If you dont want any confirmation box to be displayed to the user, dont use any return statement.

Given you know the above event you can use that event to handle any type of business logic you want to happen before the user leave the current page.

Hope this will be useful to you.

For additional information you can visit http://www.hunlock.com/blogs/Mastering_The_Back_Button_With_Javascript

4 comments:

  1. I liked it , good information it helps lot...

    ReplyDelete
  2. Very Useful info. It helps a lot...

    ReplyDelete
  3. I've tried n a web application but it's not working ....


    please attach any example file

    ReplyDelete