I'm new to using the html 5 history object. I tried the following code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
history.pushState({somethinggoeshere:'but what?'}, 'Does a title go here?', '?begin=true');
window.addEventListener('popstate', function(event) {
console.log('popstate fired!');
console.log(event.state);
});
function dosomething()
{
document.getElementById('box').style.display = 'block';
document.getElementById('iframe').src = 't2.html';
history.pushState({somethinggoeshere:'but what?'}, 'Does a title go here?', '?complete=true');
}
</script>
</head>
<body>
<a onclick="dosomething();">Show box</a>
<div id="box" style="background:red; height:100px; display:none;"></div>
<iframe id="iframe" src="t1.html"></iframe>
</body>
</html>
When I press Show box, a red box appears below, and the contents of the iframe goes from t1.html to t2.html. When I press the back button in the chrome browser, the contents of the iframe goes back to t1.html , but the red box does not disappear.
Why does the back button restore the content of the iframe but not the css styles of the redbox (back to display:none);
The browser's history is just a list of URLs. pushState
lets you associate an object with a URL in the history, a "state" if you will. This object is the 1st parameter passed to pushState
.
Just like when browsing the history "normally", the actual state of the page isn't saved. That's up to you. In your object, you should save that the red box should be shown, and in onpopstate
show it again.
Such as:
history.pushState({
redBox: document.getElementById('box').style.display
}, 'Most browsers ignore this parameter.', '?complete=true');
Then in onpopstate
, set document.getElementById('box').style.display
to event.state.redBox
.
EDIT: The iFrame is like a new browser window, so it has its own history object. When you click "back", the iFrame sees that and goes back in history. You need to have window.addEventListener('popstate', function()
inside the page in the iFrame too.
来源:https://stackoverflow.com/questions/13633691/html-5-history-restores-some-changes-and-not-others