Wednesday, 27 June 2007

Back button woes - saving a page before leaving it.

I have a web page used to collate orders - it holds all the data in view state and when the save button is hit everything is transferred to the database. When demoing this to the client they accidentally hit the back button on the mouse, this caused all the data to be lost :(.

I didn't think there was much I could do to stop this from occurring - but a post from the 4 Guys From Rolla helped!

Basically you add this little bit of javascript to the top of the page:

<script type="text/javascript"> 
var needToConfirm = true;
window.onbeforeunload = confirmExit;
function confirmExit()
if (needToConfirm)
return 'Do you want to save before exiting?';
function DisableNavigationWarning()
needToConfirm = false;
And on the save/cancel button add "needToConfirm=false;" to the onclientclick property - shown below:

<asp:Button ID="btnSaveOrder" OnClientClick="needToConfirm = false;" runat="server" OnClick="btnSaveOrder_Click" Text="Save Order" />
Now if the user tries to navigate away from the page without first hitting save or cancel they get the following pop up:-

Click OK and they navigate away as before, click cancel and they stay on the page - perfect!

Hope this helps!


This has been tested on IE6, IE7, and Firefox - no idea if this works on Safari or Opera

1 comment:

Anonymous said...

Just a small comment, but I think the UI is a touch confusing. You are asking 'Do you want to save before exiting?' when in fact the Cancel button saves and the Ok button loses your changes...