简体   繁体   中英

Save/ restore all javascript variables on browser back/forwd button click

I want to restore an ajax entire modified page along with the javascript variables in memory when the browser back button is pressed. It was added to the brwoser history manually using window.history.pushState() . I'm trying to save/restore the page using :

            function changeURL(){
               window.history.pushState(document.body.innerHTML,"","...");
            }

            window.onpopstate = function(e){
                if(e.state){
                    document.body.innerHTML = e.state;
                }
            };

Seemingly this works but just a problem that the javascript variables that were in memory at the time page was loaded are no longer there as they are modified by subsequent ajax requests but I didn't made any provision to restore them on pressing back button. How can I restore all those values to the variables ?

  1. Write a function that will serialize all of the variables you want to track into some easy to manage format (I'd suggest JSON).
  2. Write a second function that can accept the serialized data and parse/deserialize it, restoring variables as it goes (this will be a mirror image of your first function).
  3. Find some reasonable place to store your serialized state so that it is preserved across page loads. Personally I've used cookies for this in the past, though you can also use localStorage or any other mechanism you prefer.
  4. Add code to your page to store/update the serialized state either every time the state changes, or at least at some point right before the user leaves the page.
  5. Add code to your page to check for stored/serialized state when the page loads, and load it if it exists.

Edit: I'd also recommend not treating the entirety of document.body.innerHTML as your serialized "state". It should be possible to isolate the variables that you are using to modify the HTML content, and use that as your state. Then you can just regenerate the corresponding HTML by re-applying your variables.

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