Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is event.state on window.onpopstate empty when pushing with same location.href (or empty)

When pushing to history and setting data without changing URL:

window.history.pushState({
    stateName: "myStateName", 
    randomData: window.Math.random()
}, "myStateName", location.href);

.... and then listen to the pop event and trigger it by pressing the Back button in the browser:

window.onpopstate = function(event) {
  console.log(event.state); //logs null
}

You will most of the time get null as the state value instead of:

{
    stateName: "myStateName", 
    randomData: 0.34234234234
}

How can I solve this and why does this happen?

like image 948
PerMafrost Avatar asked Feb 06 '15 10:02

PerMafrost


People also ask

What triggers Onpopstate?

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history. back() or history. forward() in JavaScript). Browsers tend to handle the popstate event differently on page load.

What is the purpose of the event window Onpopstate?

The window. onpopstate event is fired automatically by the browser when a user navigates between history states that a developer has set. This event is important to handle when you push to history object and then later retrieve information whenever the user presses the back/forward button of the browser.


1 Answers

This is a weird issue and according to me, it's not documented enough. I had loads of trouble with looking for a solution to this problem. After an hour of frustrated googling and trying/coming up with different solutions I noticed that it started working when I pushed the state twice (or more). It became clear that event.state referred to the second last state that was pushed.

So the answer to making this work is to push twice, listen once.

window.history.push(..);
window.history.push(..);

I hope this helps someone!

like image 156
PerMafrost Avatar answered Oct 10 '22 06:10

PerMafrost