Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to change url without changing browser history

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.

like image 695
Paritosh Piplewar Avatar asked Jan 05 '14 18:01

Paritosh Piplewar


People also ask

How do I change URL without changing pages?

There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it ( document. location ) then it will reload the page.


1 Answers

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.

like image 93
adeneo Avatar answered Sep 17 '22 02:09

adeneo