By Robinicks


2009-05-05 10:54:05 8 Comments

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";  // Sadly this reloads

18 comments

@Haimei 2015-06-10 18:25:35

Here is my solution (newUrl is your new URL which you want to replace with the current one):

history.pushState({}, null, newUrl);

@Craig Jacobs 2016-08-29 00:14:28

Best to test first with if (history.pushState) {} Just in case old browser.

@kkatusic 2017-11-09 10:19:34

This doesn't work any more you will get in Firefox: The operation is insecure.

@Prathamesh Rasam 2015-08-15 11:55:32

Use history.pushState() from the HTML 5 History API.

Refer to the HTML5 History API for more details.

@Alireza 2017-07-02 08:03:02

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 exist, so if you do some JavaScript code which be 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);
}

@J0ANMM 2018-07-17 11:54:47

Would window.onhashchange and window.onpopstate do the same in this case?

@MD. Atiqur Rahman 2018-09-14 13:54:23

How to load page contents as well? It just replaces the URL

@AndroidDev 2018-09-15 16:27:28

Load content as you would normally do with ajax.

@Huy Truong 2017-07-13 04:04:41

Use window.history.pushState("object or string", "Title", "/new-url"), but it will still send a new URL request to server.

@Nathan Tuggy 2017-07-13 04:26:06

A quick search shows pushState has been mentioned only 14 times in other answers!

@Sheetal Kumar Maurya 2018-10-15 19:24:39

Use:

    let stateObject = { foo: "bar" };
    history.pushState(stateObject, "page 2", "newpage.html");

You can see it in blog post Update URL of browser without page reload.

@nabster 2019-01-03 22:13:09

Please consider adding more description here instead of cut-pasting a link to your blog post.

@Nate 2009-12-13 22:57:11

You can add anchor tags. I use this on my site http://www.piano-chords.net/ so that I can track with Google Analytics what people are visiting on the page.

I just add an anchor tag and then the part of the page I want to track:

var trackCode = "/#" + urlencode($("myDiv").text());
window.location.href = "http://www.piano-chords.net" + trackCode;
pageTracker._trackPageview(trackCode);

@OIS 2011-09-28 20:54:52

How does that work with search engine indexing?

@David Murdoch 2010-07-28 15:30:31

This can now be done in Chrome, Safari, Firefox 4+, and Internet Explorer 10pp4+!

See this question's answer for more information: Updating address bar with new URL without hash or reloading the page

Example:

 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.

@David Murdoch 2011-10-03 17:56:33

@manakor "This can now be done in Chrome, Safari, FF4+, and IE10pp3+!" ... Looks like it will.

@Dominic 2012-05-01 09:35:06

How does facebook do it in IE7 then?

@Tsukimoto Mitsumasa 2012-09-19 19:58:30

Sadly, this is not working on IE9.

@David Murdoch 2012-09-19 22:21:25

@CHiRiLo check out history.js which provides a fallback for browsers that don't support the HTML5 history API.

@Izkata 2012-11-08 22:26:33

@infensus If there's a # sign in the URL somewhere, that trick has existed for years..

@Scott Tesler 2012-12-13 02:55:20

What does the "pp4+" part of "IE10pp4+" mean?

@David Murdoch 2012-12-13 21:23:04

platform preview 4

@user962206 2012-12-20 16:16:13

will a button should call the 'processAjaxData' method?

@user962206 2012-12-20 16:44:18

@DavidMurdoch is the processAjaxData method should be placed inside an event??

@think123 2013-01-02 04:31:46

could you explain in more detail about the processAjaxData() function?

@David Murdoch 2013-01-02 21:13:16

processAjaxData is just an example; it is only meant to show you a typical use-case for history.pushState.

@think123 2013-01-15 05:25:12

then how would the response object work?

@Alvaro 2013-05-20 05:42:24

Can you know when the back and when the forward button is pressed?

@trek711 2013-07-11 15:22:55

Is there an opportunity to load the fragment into the content div again when I refresh the page manually?

@LeSam 2013-07-26 12:39:25

@Izkata can you explain me how to do it with the # sign ?

@Izkata 2013-07-26 12:47:54

@user2372006 Not a chance of it here. Try asking a question.

@user2166538 2013-09-01 18:15:16

using your function, my page title returns undefined as does the content html.

@Jeremy 2013-09-01 20:56:46

How is the processAjaxData supposed to be called? Is the idea that the caller has already extracted the page title and html and put them into a { pageTitle: ..., html: ... } object, or is that the interface already provided by some built-in object?

@David Murdoch 2013-09-03 14:17:40

In this example, the AJAX data's response object IS { pageTitle: ..., html: ... }; in other words: that object was put together by the server and sent in response to the XHR request.

@pascalvgemert 2014-07-03 08:31:29

e.state can also be e.originalEvent.state in my case

@sonam Sharma 2015-11-13 18:53:20

how to call this function ?? i mean what to put in response ??

@Ankit 2016-01-26 21:41:31

@ScottDavidTesler May be pp4+ means public preview 4+

@HoldOffHunger 2016-05-10 13:46:07

What's response?

@Dan Nissenbaum 2016-09-03 02:36:08

Does the URL have to be an absolute path, or can it be relative?

@Dan Nissenbaum 2016-09-03 02:49:40

I've answered my own question - yes (and see Vivart's answer below).

@Oleg Abrazhaev 2018-10-26 09:03:23

@Dominic they have normal single page app I guess

@Suraj 2015-10-27 08:33:13

Below is the function to change the URL without reloading the page. It is only supported for HTML5.

  function ChangeUrl(page, url) {
        if (typeof (history.pushState) != "undefined") {
            var obj = {Page: page, Url: url};
            history.pushState(obj, obj.Page, obj.Url);
        } else {
            window.location.href = "homePage";
            // alert("Browser does not support HTML5.");
        }
    }

  ChangeUrl('Page1', 'homePage');

@Green 2015-11-26 18:06:06

What is page?

@Snook 2016-05-27 07:41:38

@Green, page is a short title for the state to which you're moving. Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. From: developer.mozilla.org/en-US/docs/Web/API/…

@Jeremy Warne 2011-04-19 11:43:59

If what you're trying to do is allow users to bookmark/share pages, and you don't need it to be exactly the right URL, and you're not using hash anchors for anything else, then you can do this in two parts; you use the location.hash discussed above, and then implement a check on the home page, to look for a URL with a hash anchor in it, and redirect you to the subsequent result.

For instance:

1) User is on www.site.com/section/page/4

2) User does some action which changes the URL to www.site.com/#/section/page/6 (with the hash). Say you've loaded the correct content for page 6 into the page, so apart from the hash the user is not too disturbed.

3) User passes this URL on to someone else, or bookmarks it

4) Someone else, or the same user at a later date, goes to www.site.com/#/section/page/6

5) Code on www.site.com/ redirects the user to www.site.com/section/page/6, using something like this:

if (window.location.hash.length > 0){ 
   window.location = window.location.hash.substring(1);
}

Hope that makes sense! It's a useful approach for some situations.

@Robin Day 2009-05-05 10:57:05

NOTE: If you are working with an HTML5 browser then you should ignore this answer. This is now possible as can be seen in the other answers.

There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it (document.location) then it will reload the page.

One obvious reason being, you write a site on www.mysite.com that looks like a bank login page. Then you change the browser url bar to say www.mybank.com. The user will be totally unaware that they are really looking at www.mysite.com.

@Robinicks 2009-05-05 10:59:25

I don't want to change the domain, only the path and file name.

@Robin Day 2009-05-05 11:04:36

This still doesn't stop potential security risks as the browser has no idea that domain/mysite and domain/othersite are both considered "safe" by the user. Maybe the question should be why do you want to change the URL? If it is to obscure it from the user, you could simply run your application within an iframe.

@Nick Berardi 2009-12-14 03:54:38

You can actually do this with Flash. It will allow you to modify the URL without making a request. This is possible because Flash operates outside of the browser, but very tightly with it.

@dusoft 2009-12-14 09:08:16

you can change hash / fragment, but definitely not the location / path.

@Sunday Ironfoot 2010-04-29 15:58:37

I have to say there are perfectly valid reasons for wanting to modify the URL in the address bar client-side. For instance, if you have a table of data with paging, sorting and filtering, and want those things to be Ajax powered, but still update the URL so that the current state of the page is bookmarkable. I can understand the security risks with modifying the domain name (phishing etc.), but why don't browsers allow just the part of the URL to the right of the top level domain to be modifiable via script?

@David Murdoch 2010-07-28 15:31:29

this answer is no longer 100% true. See my answer for details.

@Jean Vincent 2010-09-13 23:53:59

The use case is indeed when using Ajax, you may display another document but do not want to reload, yet you want the document to be bookmarkable. In these cases one would like to change the path of the URL without changing the domain, which should be fine from a security standpoint.

@Mat J 2011-09-10 08:07:50

wondering how facebook's photo viewer modifies the url on next/previous navigation without reloading the entire page but only the image. They are not changing the #hash but the query string (?id=query_string) Is that html5?

@Andrey Nikishaev 2011-12-23 15:26:53

If there is no way to do this then how this is implemented in google+ photos. There, when you click on the next photo(in fullscreen view) url changed but page not reloaded, and only needed image is uploaded.

@Parag Gangil 2014-06-11 09:35:40

@SundayIronfoot If the browser allows to change part of URL to the right of the top level domain, then someone using online proxies (like free-proxy-online.appspot.com) could become a victim of phishing attack.

@Vivart 2010-08-17 13:59:35

HTML5 introduced the history.pushState() and history.replaceState() methods, which allow you to add and modify history entries, respectively.

window.history.pushState('page2', 'Title', '/page2.php');

Read more about this from here

@Ciro Santilli 新疆改造中心996ICU六四事件 2014-07-09 16:05:59

May not work on file:/// for safety reasons, e.g. Firefox 30. Test on localhost with python -m SimpleHTTPServer.

@jned29 2016-05-24 03:27:56

I used this on codeigniter.

@Alexis Wilke 2016-06-04 04:23:06

The first parameter is expected to be an object, not just a string.

@Craig Jacobs 2016-08-29 00:13:57

IMO this is really the best answer. If all you want to do is update the current URL ({}, null, strNewPath) is all you need to do. Best to test first with if (history.pushState) {}

@Andrew 2017-01-03 18:20:31

you can just enter null for the first 2 parameters if you dont want to change them. You can also use an absolute url for the third parameter.

@RedClover 2017-02-24 15:56:27

It would be nice if you put some more information just IN the answer. I don't have idea, what parameter 1 does.

@n00bstacker 2018-03-16 18:41:59

How does this impact GA? I would like to change view upon search, capture the url in GA on change and avoid reload.

@Shine 2014-01-24 08:49:08

Before HTML5 we can use:

parent.location.hash = "hello";

and:

window.location.replace("http:www.example.com");

This method will reload your page, but HTML5 introduced the history.pushState(page, caption, replace_url) that should not reload your page.

@OSWorX 2018-05-12 09:00:41

The problem with history.pushState(..) is, that if you want to redirect to another domain, the cross domain policy come in effect. While with window.location.replace(..)redirecting to another domain is possible.

@George Filippakos 2012-11-19 10:32:31

You can also use HTML5 replaceState if you want to change the url but don't want to add the entry to the browser history:

if (window.history.replaceState) {
   //prevents browser from storing history with each change:
   window.history.replaceState(statedata, title, url);
}

This would 'break' the back button functionality. This may be required in some instances such as an image gallery (where you want the back button to return back to the gallery index page instead of moving back through each and every image you viewed) whilst giving each image its own unique url.

@Erenor Paz 2013-09-05 13:55:24

As pointed out by Thomas Stjernegaard Jeppesen, you could use History.js to modify URL parameters whilst the user navigates through your Ajax links and apps.

Almost an year has passed since that answer, and History.js grew and became more stable and cross-browser. Now it can be used to manage history states in HTML5-compliant as well as in many HTML4-only browsers. In this demo You can see an example of how it works (as well as being able to try its functionalities and limits.

Should you need any help in how to use and implement this library, i suggest you to take a look at the source code of the demo page: you will see it's very easy to do.

Finally, for a comprehensive explanation of what can be the issues about using hashes (and hashbangs), check out this link by Benjamin Lupton.

@Steve 2009-05-13 22:14:44

parent.location.hash = "hello";

@Robinicks 2009-05-14 18:26:00

I want to change the URL, not just the hash -- #mydata

@Matthew Lock 2009-11-24 08:32:02

Changing the hash can be useful in ajax as it's a kind of state without using cookies, is bookmarkable, and compatible with browser back buttons. Gmail uses this nowadays to make it more browser friendly.

@noisy 2013-07-17 07:07:03

@Jarvis: what is the difference?

@RedYetiCo 2014-11-06 22:07:12

@noisy Server side tracking cannot see hashes unless sent to the tracking service explicitly.

@catbadger 2017-02-01 13:57:23

this is not useful if you're using an mvc framework that routes on hash, for example backbone.

@Thomas Stjernegaard Jeppesen 2012-11-21 11:09:02

The HTML5 replaceState is the answer, as already mentioned by Vivart and geo1701. However it is not supported in all browsers/versions. History.js wraps HTML5 state features and provides additional support for HTML4 browsers.

@Hexagon Theory 2009-05-05 12:23:52

Assuming you're not trying to do something malicious, anything you'd like to do to your own URLs can be magicked into being with htaccess.

@samvermette 2010-03-02 03:29:07

htaccess only works with server requests. Hashtags are not sent to the server, therefore htaccess rewriting can not work.

@HoldOffHunger 2018-08-29 21:16:58

htaccess redirects let users visit address A and see the webpage at address B, while keeping address A. I think OP wants to do the opposite: user visits address A and sees webpage of address A with address of B. Interesting suggestion, though, because I had to think it out!

@Gumbo 2009-05-05 10:58:53

Any changes of the loction (either window.location or document.location) will cause a request on that new URL, if you’re not just changing the URL fragment. If you change the URL, you change the URL.

Use server-side URL rewrite techniques like Apache’s mod_rewrite if you don’t like the URLs you are currently using.

@Robinicks 2009-05-05 11:09:33

Can I use "location.pathname"??

@Gumbo 2009-05-05 11:47:27

No, changing that attribute will cause a request too.

Related Questions

Sponsored Content

53 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5662408 View
  • 7036 Score
  • 79 Answer
  • Tags:   javascript arrays

14 Answered Questions

[SOLVED] Encode URL in JavaScript?

3 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

16 Answered Questions

[SOLVED] What is the maximum length of a URL in different browsers?

  • 2009-01-06 16:14:30
  • Sander Versluys
  • 1100456 View
  • 4442 Score
  • 16 Answer
  • Tags:   http url browser

14 Answered Questions

[SOLVED] How to change the URI (URL) for a remote Git repository?

  • 2010-03-12 12:48:47
  • e-satis
  • 1238949 View
  • 3135 Score
  • 14 Answer
  • Tags:   git url git-remote

86 Answered Questions

[SOLVED] How do JavaScript closures work?

20 Answered Questions

[SOLVED] Get the current URL with JavaScript?

  • 2009-06-23 19:26:45
  • dougoftheabaci
  • 2570470 View
  • 2723 Score
  • 20 Answer
  • Tags:   javascript url

31 Answered Questions

[SOLVED] What is the difference between a URI, a URL and a URN?

  • 2008-10-06 21:26:58
  • Sean McMains
  • 1052926 View
  • 4058 Score
  • 31 Answer
  • Tags:   http url uri urn rfc3986

Sponsored Content