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.
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.
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With