Ad

Javascript: Is There Something Like SessionStorage Or LocalStorage For One Page Only?

- 1 answer

I am currently working on a website using ASP.NET MVC and HTML/JavaScript. On this website I have a page with a data form which contains multiple text fields, comboboxes, datetime pickers and other controls (some of them are from the jQuery UI extension) where the user can enter data.

Now I have the requirement that the entered data should not get lost when refreshing the page as currently all fields in the form become blank when the page is refreshed.

I have already implemented a solution which stores everything the user enters in the sessionStorage and restores it when the user refreshes the page. However, the sessionStorage is not ideal for this purpose because the data will even get restored when the user navigates to a completely different page on the website and then navigates back to the page that contains the data form.

Is there any way to store data via JavaScript that works just like the sessionStorage (or localStorage) but is automatically cleared when the user navigates to a different page? If not, is there at least a simple way how I could manually clear the sessionStorage whenever the user navigates to another page?

Ad

Answer

You can handle document ready event in your layout page, then you can check by your page URL.

<script>

    $(document).ready(function () {
        if (window.location.href != 'your url') {
            // reset all data
        }
        else {
            // restore data from local storage
        }
    });
</script>
Ad
source: stackoverflow.com
Ad