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

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) {
  }, false);

I have also tried:

<script type="text/javascript">
  window.onpopstate = function() {

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



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.



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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.