Modifying a query string without reloading the page

Sonic Soul picture Sonic Soul · Jun 10, 2012 · Viewed 104.5k times · Source

I am creating a photo gallery, and would like to be able to change the query string and title when the photos are browsed.

The behavior I am looking for is often seen with some implementations of continuous/infinite page, where while you scroll down the query string keeps incrementing the page number (http://x.com?page=4) etc.. This should be simple in theory, but I would like something that is safe across major browsers.

I found this great post, and was trying to follow the example with window.history.pushstate, but that doesn't seem to be working for me. And I'm not sure if it is ideal because I don't really care about modifying the browser history.

I just want to be able to offer the ability to bookmark the currently viewed photo, without reloading the page every time the photo is changed.

Here is an example of infinite page that modifies query string: http://tumbledry.org/

UPDATE found this method:

window.location.href = window.location.href + '#abc';

it appears to work for me, but i am on a new chrome.. it would probably cause some issues with older browsers?

Answer

Fabio Nolasco picture Fabio Nolasco · Oct 9, 2013

If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:

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

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. And of course that it requires modern browsers that can process HTML5 History API.

For more information:

http://diveintohtml5.info/history.html

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