Preserve page state for revisiting using browser back button

前端 未结 4 1148
终归单人心
终归单人心 2020-12-15 07:31

I have a page that dynamically loads content based on a user pushing a button:

${document).ready(function)
{
    $(\"#myButton\").click(function()
    {
             


        
相关标签:
4条回答
  • 2020-12-15 08:11

    epignosisx and Malcolm are both right. It's also known as "deep linking". We used the JQuery Address Plugin to deal with this in a recent Play application.

    http://www.asual.com/jquery/address/

    0 讨论(0)
  • 2020-12-15 08:29

    The browser loads the page as it was first received. Any DOM modifications done via javascript will not be preserved.

    If you want to preserve the modifications you will have to do some extra work. After you modify the DOM, update the url hash with an identifier that you can later parse and recreate the modification. Whenever the page is loaded you need to check for the presence of a hash and do the DOM modifications based on the identifier.

    For example if you are displaying user information dynamically. Every time you display one you would change the url hash to something like this: "#/user/john". Whenever the page loads you need to check if the hash exists (window.location.hash), parse it, and load the user information.

    0 讨论(0)
  • 2020-12-15 08:30

    Implementing browser back functionality is hard. It gets easier when you use a plugin like jquery.history.js.

    http://tkyk.github.com/jquery-history-plugin/

    0 讨论(0)
  • 2020-12-15 08:32

    A technique I use for this is to serialize state to JSON, store it in the hash string, and then read it back when the page is navigated back to. This has been tested in IE10+, Firefox, Chrome.

    Example:

    // On state change or at least before navigating away from the page, serialize and encode the state
    // data you want to retain into the hash string
    
    window.location.hash = encodeURIComponent(JSON.stringify(myData));
    
    // If navigating away using Javascript, be sure to use window.location.href over window.location.replace
    
    window.location.href = '/another-page-url'
    
    ....
    
    // On page load (e.g. in an init function), if there is data in the #hash, overwrite initial state data
    // by decoding and parsing the JSON string
    
    if (window.location.hash) {
    
        // Read the hash string omitting the # prefix
    
        var hashJson = window.location.hash.substring(1);
    
        // Restore the deserialized data to memory
    
        myData = JSON.parse(decodeURIComponent(hashJson));
    }
    
    0 讨论(0)
提交回复
热议问题