Navigating back to Search Page with same state (JavaScript)

前端 未结 2 577
一向
一向 2021-01-23 09:47

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.

e.g.

2条回答
  •  迷失自我
    2021-01-23 10:39

    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");
    

提交回复
热议问题