Search code examples
javascriptphpbrowser-history

JavaScript - How to tell if the user has just returned to the previous page


I have a two page process for the user. When the user submits the first page via ajax, it saves the values to the session. If the user goes back in their browser, the first page UI is reloaded to its previous state with JavaScript using the session values.

However, the first page can also be pre-filled via query string parameters. If the query string parameters are present, any existing session needs to be ignored, otherwise the user will never be able to follow new links to the first page pre-filled with a new set of values (it will always just override the values with the same ones from their last session).

The session only gets cleared if they complete Page 2.

I have one problem with this. If the user goes to the second page and then goes back via their browser history, back button, etc., we can assume they do in fact want to see the previous page with their current session values in it, and not reset that first page to whatever was in the query string when they originally came to page 1.

To clarify the logic here:

Page 1

Does user have existing session?
     |
    No ---- Is query string present?
     |           |
     |          No  ---- Load default view
     |           |
     |          Yes ---- Load from query string
     |
     |
    Yes --- Is query string present?
                 |
                No  ---- Load from session
                 |
                Yes ---- Did user just come directly back from Page 2?
                             |
                            No  ---- Load from query string
                             |
                            Yes ---- Load from session

It is the very last piece here which I'm not sure how to do in a tidy way. I know I could solve this by logging every page request on the site and checking if the previous one was Page 2, but I'd like to know if there is a simpler way with less overhead, just using JavaScript.


Solution

  • You could use the History API to replace the current location entry, when the user arrives on page 1 - with the query-string-less URL of page 1.

    If they then go back from page 2, it should load page 1 without any GET parameters.