Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle user arrival-at-page via browser-back-button?

  1. User Visits Page A and clicks around a few times, adjusting page-state as he/she goes.
  2. Page A eventually redirects user to Page B
  3. User clicks browser back button, sees Page A again in browser

I need to perform some interface clean-up on step 3.

How do I capture this event in Page A?

like image 838
Brian Webster Avatar asked Aug 11 '11 15:08

Brian Webster


3 Answers

I'm going to make a few assumptions to present a way to do this that isn't fully reliant on javascript:

  1. You noted in the comments to another answer that this is an ASP.NET app. I am going to assume that you only care about the back button where it is being pressed from another page in your ASP.NET app.
  2. You control the server-side code executed in the ASP.NET code-behind for both the page in question and for the page(s) it will need to "back" out of.

If both of those conditions are true, then you should be able to use a Session variable! Just set the current page into a currPage variable maintained by session on all of the related pages. Then when the page is loading, check that and use it to either adjust the way the page is shown directly, or to write a value to a hidden field/input/div, which your javascript can read and use to react appropriately.

If you go the JS-read-and-execute route, you'll want to test to ensure the events fire properly on all browsers after a load-from-back-button. As mentioned in the link from Rionmonster, sometimes onload events may not fire after a back-button. If you see issues from this, then use the tricks mentioned there to get around it.

This type of solution should work for any web-app that employs server-side code capable of interacting with Session variables (e.g. it will also work for PHP, Python, and many others).

Note: There's a chance this won't be quite as elegant as it sounds. In a lot of cases browsers may not actually pull a fresh page from the server after the back button is pressed. If testing reveals this to be an issue, you may need to employ some AJAX techniques to populate the information fresh to the JS after the back button-press.

like image 82
Jeffrey Blake Avatar answered Oct 04 '22 23:10

Jeffrey Blake


Aside from possibly setting a cookie, you can't due to a browser security restriction. A work around would be to check if the user navigates away from the page via onbeforeunload or onunload fire.

like image 25
Robert Avatar answered Oct 04 '22 21:10

Robert


Would it be possible in your scenario to use the URL hash to navigate to page B and use AJAX and jQuery to load the new page? Therefore, the browser is not actually leaving the page. When the user navigates back, all they will do is change the URL hash back. You could then capture the hashchange event to see if the user has navigated back to page A.

like image 28
Connell Avatar answered Oct 04 '22 21:10

Connell