How do I modify the URL without reloading the page?

Asked  Aug 01, 09:02 pm 48 Views Add Your Answer
Asked  Aug 01, 09:02 pm

Is there a way I can modify the URL of the current page without reloading the page?

I would like to access the portion before the # hash if possible.

I only need to change the portion after the domain, so it's not like I'm violating cross-domain policies.

window.location.href = "www.mysite.com/page2.php";  // this reloads

0 Dislikes
0 Comments

1 Answers

Added  Aug 01, 09:17 pm

Use window.history.pushState method

function processAjaxData(response, urlPath) {
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html, "pageTitle":response.pageTitle}, "", urlPath);
 }

You can then use window.onpopstate to detect the back/forward button navigation:

window.onpopstate = function(e){
    if(e.state){
        document.getElementById("content").innerHTML = e.state.html;
        document.title = e.state.pageTitle;
    }
};

For a more in-depth look at manipulating browser history, see this MDN article.

0 Likes 0 Dislikes
0 Comments
×
Google login
SignUp with Email
X