window.onpopstate is not working; nothing happens when I navigate back to page

Erica Stockwell-Alpert picture Erica Stockwell-Alpert · Apr 7, 2015 · Viewed 33.7k times · Source

I'm trying to add window.onpopstate on one of the pages on my site, but nothing is happening. I put this script on the page:

<script type="text/javascript">
  window.addEventListener('popstate', function(event) {
    if (event.state) {
      alert(event.state);
    }
  }, false);
</script>

I have also tried:

<script type="text/javascript">
  window.onpopstate = function() {
    alert("popped!");
  }
</script>

However, I don't get any alerts when I navigate back to the page.

Answer

Paolo picture Paolo · Apr 7, 2015

You get a popstate event only if you add one or more history entry/entries and later the user clicks the back button in the browser.

Adding entries to the browser history lets you change the URL (just as the user navigates to another page) but without actually loading a new page.

You add a history entry with pushState method:

history.pushState({}, '', '/newpage');

As you add one entry and the user clicks back the URL switches back to the previous one but the page at that address is not loaded. A popstate event is triggered instead.

See https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history


Exceptions:

Older browsers don't support popstate events and manipulation of the browser's history.

Some browsers (ex. Safari) trigger a popstate event also when the page is actually loaded.