Take the 2-minute tour ×

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>
                <script type="text/javascript">

window.addEventListener('popstate', function(event) {
  console.log('popstate fired!');


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');
                <a onclick="showbox();">Show box</a>
                <div id="box" style="background:red; height:100px; display:none;"></div>

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?

share|improve this question
add comment

1 Answer

up vote 0 down vote accepted

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 to pushState with 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 (in onpopstate).

(Note: you can pass anything that can be JSON.stringifyed to pushState.)

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.state is not null then.

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.

share|improve this answer
when you say "pushing the current state of the page", does "current state" include the state of #box being display=block ? Does the browser remember to retain visibility of the box if browsed to again from history? –  John Nov 29 '12 at 19:45
@John: Sorry if that was confusing. It's just like browsing normally through the history. The browser will only return you the object passed as the 1st parameter to pushState. It won't remember anything about the page, except the URL. That's up to you. –  Rocket Hazmat Nov 29 '12 at 19:47
Thanks fo rthe answer. I followed up with another basic question here: stackoverflow.com/questions/13633691/… –  John Nov 29 '12 at 19:58
add comment

Your Answer


