I have a main page where you can load other pages into a container. When a page is loaded you're still on the main page but the browser URL should be set to the URL of the loaded page. When closing the loaded page, the URL should be reset to the url of main page.
I would like to solve this by simply using history.replaceState
or pushState
, and not having to go back in the browser history (because going back causes some browsers to refresh and messes up scrolling).
My current solution is
clickLoadPage => (pageUrl) {
closeOtherLoadedPages();
if (isOnMainPage())
pushState(pageUrl)
else
replaceState(pageUrl)
}
clickUnloadPage => () {
replaceState(mainpageUrl);
}
Note: It's designed to only have one page loaded at any time. Example: First load page1. Then load page2. Desired effect: page1 is closed, the url is replaced by page2. At that state, going Back in the browser would return to the main page url.
The problem is that every time you load a new page, and then close it, a new state with main page is added to window history. There should only be 1 of those states but I end up with several.
Is it possible to solve this some other way? I'm not that familiar with the window.history
api, is it possible to do things like remove a state, or ensuring that no duplicates states are added?
When page is being closed, you can call history.back() method to pop state from history, so url will change to previous one.
In case you've opened page 1 and you want to open page 2, you need to call method to close already opened page to pop state from history and only after that open another page.