In modern browsers and HTML5, there is a method called pushState
on window history
. That will change the URL and push it to the history without loading the page.
You can use it like this, it will take 3 parameters, 1) state object 2) title and a URL):
window.history.pushState({page: "another"}, "another page", "example.html");
This will change the URL, but not reload the page. Also, it doesn't check if the page exists, so if you do some JavaScript code that is reacting to the URL, you can work with them like this.
Also, there is history.replaceState()
which does exactly the same thing, except it will modify the current history instead of creating a new one!
Also you can create a function to check if history.pushState
exist, then carry on with the rest like this:
function goTo(page, title, url) {
if ("undefined" !== typeof history.pushState) {
history.pushState({page: page}, title, url);
} else {
window.location.assign(url);
}
}
goTo("another page", "example", 'example.html');
Also, you can change the #
for <HTML5 browsers
, which won't reload the page. That's the way Angular uses to do SPA according to hashtag...
Changing #
is quite easy, doing like:
window.location.hash = "example";
And you can detect it like this:
window.onhashchange = function () {
console.log("#changed", window.location.hash);
}
history.pushState()
is probably the right answer here, in this situation (depending on the exact circumstances...) the possibility of using a server-side redirect (such as via using Apache's RewriteRule directive) is something you might want to consider, or at least be aware of. Just thought it should be mentioned! – Doin