Search code examples
javascriptc#htmljqueryasp.net-core

How can I save the state of a web application page after reloading the page?


I have an asp net core 3.1 application, the application is very large, I want to save the state of the web page after refreshing the page. For example, the user opened a modal window and after reloading the page, the modal window is already open. I repeat, the modal window is just an example.

I thought about saving the entire page before updating and then loading it, but the problem is that the html changes, and everything else doesn't work, i.e. those scripts where initialization by click is needed, for example.

 $(document).ready(function () { 

     var text = localStorage.getItem('html');

     if (text!= null) { 
            document.body.outerHTML = text;
     }

     window.addEventListener('unload', function (event) {
         const html = document.documentElement.outerHTML;
         localStorage.setItem('html', html);
     });
 });

What are the ways to track user actions and restore the page state after a reload?


Solution

  • Saving the entire HTML page isn't a good choice and it will make the error when initializing some event handlers, I suggest you save some relevant state.

    For objects, you could also store some objects inside the localstorage,and load it from local storage.

    Like below example:

    For model popup, we could use localstorage to store the model state when clicking the button.

    Then inside the page load, we could use js to check the localstorage's model state and show it.

    Codes:

        function showCreate( ) {
    
                    // Show the modal
                    $('#createModal').modal('show');
    
                    localStorage.setItem('isModalOpen', 'true');
           
        }
    

    Check model state during page load:

        $(document).ready(function () {
            // Check localStorage for modal state
            var modalState = localStorage.getItem('isModalOpen');
            console.log(modalState);
            if (modalState === 'true') {
                $('#createModal').modal('show'); // Open the modal
            }
    
    
        });
    

    Result:

    It will auto load the model when page opening.

    enter image description here