Changing the URL query string without reloading the page using Javascript

Changing the URL query string without reloading the page using Javascript

Learn how to change the URL query string without reloading the page to give every section of your website a unique URL


URL query strings are generally used to change content on a certain page based on the given parameters. If you have a website that is dependent on asynchronous content updates, it is important to be able to change the URL query string to give the current state of the website it own unique URL that can be indexed by search engines


For this tutorial we will be using Javascript to change only the query string while leaving the rest of the URL in tact.


The main function we will be using is history.pushState() . This function takes 3 parameters: a state object which is associated with the new history state, the title of the document and the URL.


var url = window.location.href;       
var urlSplit = url.split( "?" );       
var stateObj = { Title : "New title", Url: urlSplit[0] + "?param1=5"};       
history.pushState(obj, obj.Title, obj.Url);

On line 1 we retrieve the full current URL and assigning it to the variable "url". The start of the query string is signified by the character "?" so we split the URL by this character and assign the array to a new variable "urlSplit". We then create a new object with two variables: Title, which you can assign your own string to, and Url which we assign the first part of the "urlSplit" array to, which will be the URL minus the original query string, as well as an extra string which will be the new query string.


Lastly we use history.pushState to push the new state object, title and url as the current history state.


This will change the current title and URL without re-loading the page.


You will be able to use this to change the current query string as well as the document title based on the content you are currently displaying on your page. Modern search engines such Google will load any changes made with Javascript and asynchronously loaded content based on the query string and will correctly index them.


This can be included in a function so that you can reuse it throughout your code.


function changeQueryString(searchString, documentTitle){      
    documentTitle = typeof documentTitle !== 'undefined' ? documentTitle : document.title;      
    var urlSplit=( window.location.href ).split( "?" );      
    var obj = { Title: documentTitle, Url: urlSplit[0] + searchString };      
    history.pushState(obj, obj.Title, obj.Url);      
}

Here we have a function that takes a query string and an optional title using a ternary operator to assign the current title using document.title if none is given.



Christopher Thornton@Instructobit 7 years ago
or