• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

14
Views
Strange behaviour of window.history.pushState in combination with window.history.go

I've been struggling with managing our single page application's history through the History-API.

Even though I've been able to find a working solution for my problem, there's still one thing I'm having trouble wrapping my head around.

I've simplified my code to the following:

window.onpopstate = e => console.log("Popped:", e.state.index, ", ", window.history.state.index);

for (let i = 0; i < 10; i++) {
  window.history.pushState({index: i.toString()}, "");
}

// This correctly logs "9"
console.log("Expected 9: " + window.history.state.index);
  
window.history.go(-4);

// I would expect this to log "5", but it logs "9"
console.log("Expected 5: " + window.history.state.index);

// This will log either "5" or "9", depending on the set ms
setTimeout(() => console.log("Expected 5: " + window.history.state.index), 100);

Snippet output

As described in the comments, the window.history.state does not reflect the expected value after calling window.history.go(). I was under the assumption that window.history.go() would continue upon completion and I haven't found anything about whether this is true. Strangely, the described behaviour only seems to occur if pushing multiple states and/or traversing multiple history steps, which adds to my confusion.

Maybe somebody with a deeper knowledge of how the states are managed internally could explain it and/or point me in the right direction.

about 1 month ago ·

Juan Pablo Isaza

Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.