I have my website's query string URL like:
?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1
When user go to next page (From page 1 to page 2):
We explicity increment
pn
(page number by 1) and set it in query string URL.Changed query string:
?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=2
I also store the old query string, it looks like:
?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1
I then push both to window history to change URL and save previous for browser back:
window.history.pushState(oldQS, null, newQS);
After doing this, when I am on page2, I check
window.history.state
. It stores my previous state:?budget=0-&year=0-&kms=0-&so=-1&sc=-1&pn=1
I press browser back from page2 to get back to page1. I put a breakpoint on:
$(window).on('popstate', function(e) { console.log(e.originalEvent.state) });
e.originalEvent.state
isnull
.
Observations:
- The
window.history.state
is notnull
and stores correct value when I am on page2. - It gets
null
value when I click browser back.
What I have done so far:
(Has not worked.)
put breakpoint on
hashchange
event but didn't help as there's no # in the URL.put breakpoint on every
window.history
function on my Javascript code likepushState()
,replaceState()
but none of it is getting hit when I press browser back.
I don't know what all other places/function to look at which might be changing window.history.state
to null
.
How can I figure out how and where did it become null by clicking browser back?
You asked:
Let's read the W3C HTML5 specification:
Conclusion: when the document loaded, the
history.state
is initiallynull
.Conclusion: when navigating back to the state when the document was loaded, the state triggered with the
popstate
event isnull
.