javascripturlbrowserbrowser-history

How to change all url with history.pushState


When I change my URL with history.pushState(newUrl) a few times and after that I try to go back for one page I have an error, I found out that if I do pushState(newUrl/) instead of (newUrl), this error disappears, but now pushState does not replace the URL but adds it by type The first time I called pushState on "mySite.com" I get "mySite.com/newUrl/" Second time I call pushState on "mySite.com" I get "mySite.com/newUrl/newUrl/"

Method history.replaceState gave the same result

So here is the question How can I always replace the URL without reloading the page and always get "mySite.com/newUrl/"

Well I googled it and found nothing, help me Please


Solution

  • Just use an absolute URL that you feed into pushState() or add a leading slash to the relative URL.

    According to the MDN docs:

    The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL.