I’m playing with the history object for the first time. I have the following code which I’ve been testing in chrome:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.addEventListener('popstate', function(event) {
console.log('popstate fired!');
console.log(event.state);
});
function showbox()
{
document.getElementById('box').style.display = 'block';
history.pushState({somethinggoeshere:'but what?'}, 'I put text here, but how do i verify the browser has received it?', '?showbox=true');
}
</script>
</head>
<body>
<a onclick="showbox();">Show box</a>
<div id="box" style="background:red; height:100px; display:none;"></div>
</body>
</html>
When i click on the link Show box, a red box appears. When I click on the back button in the chrome browser window, then look at console.log, event.state is null. Why is it null? Didn’t I populate this with something with history.pushState?
When you use
pushState, you are pushing the “current state” of the page (the browser doesn’t actually save the state of the page. It just associates the object passed as the 1st parameter topushStatewith the page in history) onto the browser’s history stack. When you browse to that page in the history stack, the object you pushed will appear (inonpopstate).(Note: you can pass anything that can be
JSON.stringifyed topushState.)You went back to a page in the history, but that page wasn’t added with
pushState, so it has no “state”.Try to push the “forward” button in your browser after clicking “back”. You will see that
event.stateis notnullthen.So, the object you pass is linked to the page that was pushed into the history stack, and you’ll only see it when you visit that page in the history.