Search code examples
javascriptbrowser-history

I can't seem to figure out how to manipulate the browser history


So what I am trying to do is change data based on the navigation of a user. I have 6 main category pages. From those 6 main category pages, I have 12 sub categories that the user can select.

What I am trying to achieve:

Let's say the user selects category one.

  • The user selects sub-category 1 from category 1.
  • The sub-category page is shown and removes the data not related to category 1.
  • The user selects sub-category 2 from sub-category 1 and removes the data not related to category 1.
  • The user selects sub-category 3 from sub-category 2 and removes the data not related to category 1.

So I can do the category one to sub-category 1 but how would I do it for lets says sub-category 1 to 2 and from 2 to 3...n times....? Each sub-category has to know which main category was last selected.

I have looked at but can't seem to find a solution.

window.location.hash
history.pushState("","","");
document.referrer

Typically this is a bad design and I understand that but I am limited to what I can do on the server side. So trying to develop a work around....


Solution

  • After trying to work with these and not getting the desired behavior, I was able to find the best solution through several hours of research. The only alternative I could find for passing around data on the client side between pages.

    window.location.hash
    history.pushState("","","");
    document.referrer
    

    So lets say the user navigates to category1

    You would set a session storage object

    sessionStorage.setItem('last-category', "category1");
    

    The user navigates sub-category 1. You can use this to get the session storage of an object and will show the last set operation for that object.

    sessionStorage.getItem("last-category"); -> output category1
    

    The user navigates sub-category 2

    sessionStorage.getItem("last-category"); -> output category1
    

    The user navigates to category 2 You would set the session storage object again to show category2

    sessionStorage.setItem('last-category', "category2");
    

    The user navigates to sub-category 1

    sessionStorage.getItem("last-category"); -> output category2