Vecta
Vecta

Reputation: 2350

AJAX Search Back Button

I'm trying to sort out the use of the back button with an AJAX search I built and I'm having a bit of trouble. I'm using localStorage as instructed by this previous question with this code:

// Replace the search result table on load.
if (('localStorage' in window) && window['localStorage'] !== null) {
    if ('myTable' in localStorage && window.location.hash) {
        $("#myTable").html(localStorage.getItem('myTable'));
    }
}

// Save the search result table when leaving the page.
$(window).unload(function () {
    if (('localStorage' in window) && window['localStorage'] !== null) {
        var form = $("#myTable").html();
        localStorage.setItem('myTable', form);
    }
});

I'm having trouble sorting out how to properly clear the localStorage. With the above code the users can perform a search, click a link, click back, and their results will be re-populated. However, if they leave the site and come back later or refresh the search-page their results persist. How can I work around this? Thank you!

Upvotes: 0

Views: 1037

Answers (1)

wirey00
wirey00

Reputation: 33661

Something like this?

localStorage.clear(); // <-- clears all local storage for domain

or for single items

localStorage.removeItem('myTable');

If you don't like how localStorage persists until removed manually by client, there is also sessionStorage https://developer.mozilla.org/en-US/docs/DOM/Storage

sessionStorage

This is a global object (sessionStorage) that maintains a storage area that's available for the duration of the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

// Save data to a the current session's store

sessionStorage.setItem("username", "John");

// Access some stored data

alert( "username = " + sessionStorage.getItem("username"));

The sessionStorage object is most useful for hanging on to temporary data that should be saved and restored if the browser is accidentally refreshed.

Upvotes: 3

Related Questions