the solution to what you are looking for can be implemented through the window object called history, where you add parameters to the url, without reloading the page, and change the browser's history status, so when you go back it becomes to the previous url, but without reloading, in turn, you also need to listen to the "onpopstate" event to detect when the back and forward buttons of the browser are clicked, asking then what are the parameters of the url that changed for apply your changes on the web, I leave you a couple of example functions that I did:
This function allows you to pass parameters to it in the form of an object, and it will convert them into parameters type get for the url, and then set them in the url and history of the browser:
const setUrlParams = (params) => {
if(!params)
return;
const paramsUrl = Object.entries(params)
.reduce((acum, actual, index) => (
'${acum}${index === 0 ? '?' : '&'}${actual[0]}=${actual[1]}'
), '');
const newUrl = paramsUrl;
// Según los valores que setees en los parámetros, mostras lo que quieras mostrar en tu web
// en esto que sigue se cambia el estado del history, y setea los parametros,
if(window.history.pushState)
window.history.pushState(null, null, newUrl);
};
example of calling this function:
setUrlParams({param1: 'valor1', param2: 'valor2'});
// la url cambiara a: www.tu-anterior-url.com/?param1=valor1¶m2=valor2
and then, this event will allow you to access the new url when you click on the browser arrows and that url changes, in that event you must also capture the parameters to show according to them, what you want to show on your website:
window.onpopstate = () => {
const urlChanged = window.location.href;
console.log(urlChanged);
// aquí luego agarras los parámetros de la nueva url y los usas a gusto
};
so when you go back or forward in the browser, this event will be triggered and the code you put in it.
I hope you serve, greetings!