Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
      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.

like image 482
Erica Stockwell-Alpert Avatar asked Apr 07 '15 20:04

Erica Stockwell-Alpert


2 Answers

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.

like image 58
Paolo Avatar answered Oct 31 '22 23:10

Paolo


window.onpopstate = function(event) {
  alert(`location: ${document.location}, state: ${JSON.stringify(event.state)}`)
}

history.pushState({page: 1}, "title 1", "?page=1")
history.pushState({page: 2}, "title 2", "?page=2")
history.replaceState({page: 3}, "title 3", "?page=3")
history.back() // alerts "location: http://example.com/example.html?page=1, state: {"page":1}"
history.back() // alerts "location: http://example.com/example.html, state: null"
history.go(2)  // alerts "location: http://example.com/example.html?page=3, state: {"page":3}"
like image 1
Akash Avatar answered Nov 01 '22 00:11

Akash