I am loading pages with JavaScript and I want to push the loaded page in the history.
This means that when the back button is clicked, the pushed page will be loaded.
I am not refreshing the page, I am loading it via JavaScript.
I have already tried history.pushState()
but after the back click, it did not return anything.
I can use it once when I push history and after write:
window.onpopstate = function() {
// do something
}
However, I can't use that anymore.
Perhaps I am misunderstanding window.onpopstate
...
Basic single page applications ( loading pages with javascript instead of having several seperate html/php/asp/jsp pages) works with manipulating the hash fragment of the page.
Changes to that hash will automatically create a new entry into the history so the go back
and go forward
buttons of the browser can work normally as if there's several different HTML pages.
We can then listen to the hashchange event to know when the hash changes and then just replace the content of the page. So after clicking 'page 1' below, the hashchange event is triggered and there we can call whatever function will render that page on the screen.
window.addEventListener( 'hashchange', event => {
alert( `loading ${ window.location.hash }` );
// const page = window.location.hash;
// pages[ page ].render();
});
<a href="#/page1">Page 1</a>
<a href="#/page2">Page 2</a>
So if you click 'page1', you'll get the alert 'loading page 1'.
If you then click the page 2 link, you'll also get an alert.
If we then click the back button, we get ther alert 'loading apge 1' again, since the previous link in our history was the hash containing page1.
So using this technique of 'routing', we can easily have the back/forward button work correctly, without having to resort to pushState() and popState(), which won't do much for us since we only have one HTML page and javascript to fill it.