Skip to content

JavaScript Returning Previous Value Immediately after Changing the Value

I have a single html document that simulates many pages by modifying the content and url as users click through the page.

In my JavaScript there is a place I use history.back(). This works as expected changing the url and content (even though the user really stays on the same html document). However, immediately after I use history.back() I try to get the users new window.location. This is still showing the previous url instead of the new one.

Do I need to force some type of update, refresh, calculation, garbage collection or something in-between those two lines of code so I get the new url?

Answer

Try waiting for the next tick before checking the new window.location:

history.back()
setTimeout(() => {
  console.log(window.location)
})