简体   繁体   中英

HTML5 history API popstate event returns wrong data

HTML5 history API returns wrong history state data whenever popstate event occurs. Below are some push and pop event responses (I logged in console).

JS

/*
 * JS USED TO PUSH HISTORY 
 */
var markers = [];
var markerIndexes = [];
// mapOverlays (array) is a global variable containing all marker and infowindow objects
var overlayIndex = mapOverlays.length; 
var historyData = {
    "historyDetails": {
        "append": true,
        "popState": false
    },
    "title": null,
    "url": ""
};
for (var i = 1; i < data.length; i++) {
    // this function creates a marker with infowindow and pushes marker & infowindow objects to mapOverlays array
    addActionMarkerToGMap(data[i].lat, data[i].lng, 'Demo info window', false);
}
for (var i = overlayIndex; i < mapOverlays.length; ++i) {
    markers.push(mapOverlays[i].marker);
    markerIndexes.push(i);
}
historyData.historyDetails.markerIndexes = markerIndexes;
window.history.pushState(historyData.historyDetails, historyData.title, historyData.url);


/*
 * POPSTATE EVENT HANDLER
 */
window.addEventListener('popstate', function (event) {
    if (event.state != null && event.state != "" && typeof event.state == "object") {
        var popstateData = {
            historyDetails: {
                append: event.state.append,
                popState: true, // hard coded because this is result of popstate event
                markerIndexes: event.state.markerIndexes
            }
        };
        console.log(popstateData);
    }
});

Push state 1

JSON below is pushed when first AJAX request is complete.

    {  
   "historyDetails":{
      "append":false,
      "popState":false,
      "markerIndexes":[  
         0,
         1,
         2
      ]
   },
   "title":null,
   "url":""
}

Push state 2

This JSON object is pushed to history when second AJAX request is complete.

{  
   "historyDetails":{  
      "append":true,
      "popState":false,
      "markerIndexes":[  
         3,
         4,
         5
      ]
   },
   "title":null,
   "url":""
}

Pop state 1

And this is what I get when I hit browser back button. Pop state event returns Push state 1 instead of Push state 2

{  
   "historyDetails":{  
      "append":false,
      "popState":true,
      "markerIndexes":[  
         0,
         1,
         2
      ]
   },
   "title":null,
   "url":""
}

As shown above, history API does not return most recent PUSH STATE data. Any help is highly appreciated.

Thanks

This is expected behavior and is how the history api works.

See my answer that explains how push- and popstate works, in this thread: Popstate - passing popped state to event handler

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