68

Until now, I only know that if I want to change URL without reloading the whole page i have to use HTML browser history API.

I am using this concept in my website. Let's take example. Let suppose user is on this page

 https://www.example.com/aboutus

and then he goes to product listing in which we have filters. On clicking any filters system generates new url something like this

https://www.example.com/products?brands[]=song&brands[]=samsung&condition[]=new

Internally it is just calling

history.pushState({}, 'Title', link.href);

But, it has one problem. Clicking back button takes to the previous filter. I dont want this functionality. I want , on clicking browser back button it should take to the page which is before current page. In our case, it is suppose to take to

https://www.example.com/aboutus

Thanks.

Paritosh Piplewar
  • 7,982
  • 5
  • 26
  • 41
  • well, if you are redirecting to a different page (`/products` from `/aboutus`, doesn't it reload anyway? and the whole point of the history API is to allow urls in the back menu to go to a previous state on the same page – markasoftware Jan 05 '14 at 18:18
  • You could also use – 131 Jan 05 '14 at 18:20
  • FYI, the question was asked when coursera had this functionality, currently i doubt. – Paritosh Piplewar Nov 18 '16 at 17:58
  • window.location.replace(url) will change location without adding a new entry to history, it is not bound to same origin. It will reload the page obviously – grabantot Jul 08 '22 at 05:29

1 Answers1

112

You're looking for replaceState(), it replaces the current position in the history instead of pushing a new one, like pushState() does

history.replaceState({}, 'Title', link.href);

from MDN

history.replaceState() operates exactly like history.pushState() except that replaceState() modifies the current history entry instead of creating a new one.

replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.

Remember, some functions are not available on older browsers. But there is a library that could help you out.

Popnoodles
  • 28,090
  • 2
  • 45
  • 53
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 16
    On the same MDN page above, it also states `Note that this doesn't prevent the creation of a new entry in the global browser history.` – Bill DeRose Jun 10 '16 at 23:16
  • 3
    Question: says "without changing browser history". Solution says: "replaceState() modifies the current history entry". So how do I change the URL without changing the history? I want to open URL `test.html`, click the link to `test2.html`, click button to change to address bar to `test3.html` (without actually downloading `test3.html`), then I press "back" to go to `test.html` and when I press "forward" it must go to `test2.html`, not to `test3.html`. So how do I do this? – izogfif Nov 27 '20 at 14:14