77

Is there a way to update the URL programatically without reloading the page?

EDIT: I added something in the title in post .I just want to make it clear that I don't want to reload the page

developarvin
  • 4,940
  • 12
  • 54
  • 100

10 Answers10

95

Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.

However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:

if (history.pushState) {
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
    window.history.pushState({path:newurl},'',newurl);
}

I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.

For more information:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Fabio Nolasco
  • 7,122
  • 6
  • 35
  • 32
  • Clicking "back" will remove changes but I like the idea. – Alain Tiemblo Oct 26 '14 at 19:33
  • This approach does not work in some browsers because `window.location.pathname` contains a trail slash `/`, and result value could be `http://my.domain.com/?myNewUrlQuery=1` instead of `http://my.domain.com?myNewUrlQuery=1`. – pto3 Sep 14 '18 at 08:38
39

Yes - document.location = "http://my.new.url.com"

You can also retrieve it the same way eg.

var myURL = document.location;
document.location = myURL + "?a=parameter";

The location object has a number of useful properties too:

hash            Returns the anchor portion of a URL
host            Returns the hostname and port of a URL
hostname        Returns the hostname of a URL
href            Returns the entire URL
pathname        Returns the path name of a URL
port            Returns the port number the server uses for a URL
protocol        Returns the protocol of a URL
search          Returns the query portion of a URL

EDIT: Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)

EDIT2: To make it clear, not just in a comment: You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.

morkro
  • 4,336
  • 5
  • 25
  • 35
Matt Fellows
  • 6,512
  • 4
  • 35
  • 57
  • 1
    I am looking at updating all of the url, not just hashes – developarvin Sep 20 '12 at 08:32
  • 4
    You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, and instantly have the URL say www.gmail.com and steal people's logins. – Matt Fellows Sep 20 '12 at 09:43
  • 22
    Setting `document.location` reloads the page. – Alain Tiemblo Oct 26 '14 at 19:30
  • Thanks @AlainTiemblo - if you read the whole answer you will see that I acknowledge that, with the caveats I already stated. – Matt Fellows Nov 11 '14 at 10:15
  • Good deep explanation. – M H Mar 01 '16 at 03:32
  • No - the answer is yes - just not the whole URL - the URL begin formed of the protocol, host, optional port, folder structure, page, query parameters and page location. It's possible to alter the page location `#blah` as described. – Matt Fellows Jul 26 '16 at 09:05
  • Why is this the correct answer? This reloads the page. Answer should be deleted. – Chewie The Chorkie Apr 05 '21 at 17:24
  • @ChewieTheChorkie Because it is correct? You can update parts of the URL (thus updating the URL) (Such as the # section) without reloading the page. Why should this answer be deleted? – Matt Fellows Jun 23 '21 at 07:44
7

You can use :

window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Sud
  • 135
  • 2
  • 12
  • or window.history.replaceState('obj', 'newtitle', newUrlWithQueryString) if you do not want to have the url change saved in history. – TamusJRoyce Apr 21 '19 at 22:38
5

Use

window.history.replaceState({}, document.title, updatedUri);

To update Url without reloading the page

 var url = window.location.href;
 var urlParts = url.split('?');
 if (urlParts.length > 0) {
     var baseUrl = urlParts[0];
     var queryString = urlParts[1];

     //update queryString in here...I have added a new string at the end in this example
     var updatedQueryString = queryString + 'this_is_the_new_url' 

     var updatedUri = baseUrl + '?' + updatedQueryString;
     window.history.replaceState({}, document.title, updatedUri);
 }

To remove Query string without reloading the page

var url = window.location.href;
if (url.indexOf("?") > 0) {
     var updatedUri = url.substring(0, url.indexOf("?"));
     window.history.replaceState({}, document.title, updatedUri);
}
Prasad De Silva
  • 836
  • 1
  • 12
  • 22
  • I was just looking at [Mozilla's documentation](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_replaceState()_method) for `window.history.replaceState()` I'm unsure of what the three parameters do, can you explain that? The second, specifically `document.title` doesn't seem to do anything. – tfantina Aug 10 '18 at 15:27
  • `replaceState()` operates exactly like `pushState()` so check the descriptions of the [parameters for the `pushState()` method](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method). `title` parameter is ignored for now, but they might use it in the future. – Prasad De Silva Aug 15 '18 at 17:03
4

Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.

var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);
Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
3

Yes

document.location is the normal way.

However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.

Check out this thread on SO for more info:

What's the difference between window.location and document.location in JavaScript?

Community
  • 1
  • 1
MasNotsram
  • 2,105
  • 18
  • 28
1

Prefix URL changes with a hashtag to avoid a redirect.

This redirects

location.href += '&test='true';

This doesn't redirect

location.href += '#&test='true';
Timothy Gonzalez
  • 1,802
  • 21
  • 18
0

Plain javascript: document.location = 'http://www.google.com';

This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.

Claus
  • 1,975
  • 18
  • 24
  • 1
    Yep, it causes a browser refresh. Was looking for something that does not reload. – developarvin Sep 20 '12 at 08:33
  • It should be possible to do without page refreshes but it's only supported in newer browsers as far as I know. You should go for the hash url changing instead. – Claus Sep 20 '12 at 10:00
0

You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.

If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page

Community
  • 1
  • 1
Osiris
  • 4,195
  • 2
  • 22
  • 52
-3

Yes - document.location.hash for queries

Roman
  • 504
  • 4
  • 10