Take this small example - run fiddle:
You have a page where a user can select a color. Every time they do, we generate a new history entry:
function doPushState (color) {
var state = {},
title = "Page title",
path = "/" + color;
history.pushState(state, title, path);
};
We leave the state object blank for now and set the URL to the color name (don't reload the page - that URL doesn't exist, so you will get a 404).
Now click on a red, green and blue once each. Note that the URL changes. Now what happens if you click the back button?
The browser does indeed go back in history, but our page doesn't notice that - the URL changes from '/blue' back to '/green', but our page stays at 'You have selected blue'. Our page has gone out of sync with the URL.
This is what the window.onpopstate
event and the state object are for:
- We include our selected color in our state object
function doPushState (color) {
var state = { selectedColor: color }, // <--- here
title = "Page title",
path = "/" + color;
history.pushState(state, title, path);
};
- Then we listen for the
popstate
event, so that we know when we have to update the selected color, which is this:
window.addEventListener('popstate', function (event) {
var state = event.state;
if (state) {
selectColor( state.selectedColor );
}
});
Try the updated example: run fiddle: our page now updates accordingly when the user navigates back through history.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…