How can I handle the user coming to the page through the back button?

  • The user visits page A and clicks several times, adjusting the state of the page as he / she.
  • Page Ultimately redirects the user to page B
  • The user presses the browser button, again sees page A in the browser

I need to do some cleaning of the interface in step 3.

How to capture this event on page A?

+8
javascript jquery
source share
3 answers

Besides the ability to set cookies, you cannot because of browser security restrictions. The work will be checked if the user navigates from the page through onbeforeunload or onunload fire.

+1
source share

Is it possible in your script to use a hash of a URL to go to page B and use AJAX and jQuery to load a new page? Therefore, the browser does not leave the page. When the user navigates back, all they will do is change the hash of the URL. You can then capture the hashchange event to see if the user went back to page A.

+1
source share

I am going to make a few assumptions to present a way to do this, not entirely dependent on javascript:

  • You noted in the comments of another answer that this is an ASP.NET application. I'm going to assume that you only care about the back button, where it is clicked from another page of your ASP.NET application.
  • You control the server-side code executed in the ASP.NET code for both the page in question and the pages to which it will have to "return".

If both of these conditions are true, you should use a Session variable ! Just set the current page to the currPage variable supported by the session on all linked pages. Then, when the page loads, check and use it to either configure the way the page is displayed directly, or write the value to a hidden field / input / div that your javascript can read and use to respond appropriately.

If you go along the JS-read-and-execute route, you need to test to ensure that events are displayed correctly in all browsers after loading from the back. As mentioned in the link from Rionmonster , sometimes onload events may not fire after clicking a button. If you see problems from this, use the tricks mentioned here to get around it.

This type of solution should work for any web application that uses server-side code capable of interacting with session variables (for example, it will also work for PHP, Python, and many others).

Note. There is a chance that it will not be as elegant as it seems. In many cases, browsers cannot pull out a new page from the server after clicking the back button. If testing has shown that this is a problem, you may need to use some AJAX methods to populate the information in JS after clicking the back button.

+1
source share

All Articles