简体   繁体   中英

Navigating back to Search Page with same state (JavaScript)

How do I, using JavaScript, retain the state of the search page, when a user clicks into a search result, but then goes back to the main search page.

eg

HTML : https://startech-enterprises.github.io/docs/guides/data-analytics/data-analytics.html

There are 5 elements that determine what is shown on the page:

  • What tags are clicked in the three filter menus, on the side
  • What search term is typed into the search menu bar, at the top
  • The pagination page that is selected, at the bottom

Problem is that whenever I go into the search result, and navigate back to the main search page, the search page resets itself, so I have to re-enter the search criteria again - which can be quite annoying.

If I click 'back' in the browser, the search page state is retained, but the search script stops working. Also, using the 'browser' back button only goes back one 'link' - so if the user clicks on several links in any page (returned from the search), they have to press the 'back' button many times, to get back to the main search page - which again isn't ideal.

Any ideas on how to solve this? Would seem like a fairly common problem?

The site is purely static, (generated using Markdown and Jekyll). Site interactivity is set with Vanilla JavaScript, and SASS/SCSS.

Pls do help!

Many thanks in advance.

Sachin

UPDATE: This has now been solved based on the answers given below

You can simply do it by saving the data in users device . You can do it by using cookies or by localStorage. I prefer localStorage because users can deny cookies easily. Like this-

localStorage.setItem("tags",tagItemsInAnArray);

And later localStorage.getItem("tags");

You can use localStorage to keep the search filter data. The concept is to keep all filter data in an array and keep that array in the localStorage of the browser before any redirection. Here is an official documentation with implementation of localStorage.

Here is a demo:

//before redirection
let filterData = [];
localStorage.setItem("searchFilter", JSON.stringify(filterData));

//after page-load
let cachedFilterData= JSON.parse(localStorage.getItem("searchFilter"));
if(cachedFilterData.length>0){
    //cache data exist
}

//when you need to delete cache
localStorage.removeItem("searchFilter");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM