Update URL without reloading the page using JavaScript
In this post, we will learn how to update the URL without reloading the page using JavaScript. We will see how to use the History API to manipulate the browser history and the URL, and how to handle popstate events to update our page content.
Updating the URL of a web page without reloading it is a common task that we may encounter in web development. For example, we may want to change the URL to reflect the current state of the page, such as filtering, sorting, or pagination. However, changing the URL of a web page usually triggers a page reload, which can be undesirable for various reasons. For instance, reloading the page can cause flickering, performance issues, or loss of user input. Therefore, we need a way to update the URL without reloading the page.
Fortunately, modern browsers support an HTML5 feature called the History API, which allows us to manipulate the browser history and the URL without reloading the page. In this post, we will learn how to use this feature in JavaScript to update the URL without reloading the page.
1. Overview of the History API
The History API is a set of methods and properties that enable us to interact with the browser history and the URL. The browser history is a stack of URLs that the user has visited in a browser tab. The user can navigate through the history using the back and forward buttons, or using keyboard shortcuts. The History API allows us to:
- Get the current state object of the history entry using
history.state. - Push a new state object and URL to the history stack using
history.pushState(state, title, url). - Replace the current state object and URL in the history stack using
history.replaceState(state, title, url). - Pop a state object and URL from the history stack using
history.back(),history.forward(), orhistory.go(delta).
The state object is an arbitrary JavaScript object that can store some data related to the URL. It can be retrieved using history.state or from the popstate event object. The title argument is currently ignored by most browsers, but it may be used in the future. The url argument is a relative or absolute URL that will be displayed in the address bar.
2. Updating URL without reloading the page
There are two ways in HTML5 which can update the URL of the current webpage – using either History.pushState() and History.replaceState(). Let’s discuss these in detail:
1. Using History.pushState() function
To create a new entry in the browser history and update the URL, we can use History.pushState() method. This will allow the user to go back to the previous URL using the back button. It takes the state, title, and URL as a parameter. We can call it using the DOM Window history object, i.e., window.history. Here’s an example:
|
1 2 3 4 5 6 7 8 |
const state = {page: "contact"}; const title = "Contact"; const url = "/contact"; // Suppose the current URL is https://techiedelight.com/home // Push a new state object and URL to the history stack history.pushState(state, title, url); // The new URL is https://techiedelight.com/contact |
Note that the browser won’t attempt to load the URL. Since a new history entry is created, we can press the Back button to visit the last URL.
2. Using History.replaceState() function
To modify the current entry in the browser history and update the URL, we can use History.replaceState() method. This will overwrite the previous URL and prevent the user from going back to it using the back button. For example:
|
1 2 3 4 5 6 7 8 |
const state = {page: "contact"}; const title = "Contact"; const url = "/contact"; // Suppose the current URL is https://techiedelight.com/home // Replace the current state object and URL in the history stack history.pushState(state, title, url); // The new URL is https://techiedelight.com/contact |
In both cases, we can access the state object and the URL using history.state and location.href. For example:
|
1 2 3 |
// Get the current state object and URL console.log(history.state); // {page: 'contact'} console.log(location.href); // https://techiedelight.com/contact |
We can also use any valid relative or absolute URL as an argument for pushState or replaceState. However, we cannot change the origin of the URL (the protocol, domain name, and port number), as this would violate the same-origin policy. For example:
|
1 2 3 4 5 6 7 8 9 10 11 |
// Valid URLs history.pushState(null, null, "/home"); history.pushState(null, null, "?query=foo"); history.pushState(null, null, "#section"); history.pushState(null, null, "https://techiedelight.com/contact"); // Invalid URLs // Results in error: DOMException: Failed to execute 'pushState' on 'History' history.pushState(null, null, "https://www.techiedelight.org/home"); history.pushState(null, null, "https://techiedelight.com/home"); history.pushState(null, null, "https://techiedelight.com:8080/home"); |
3. Handling Popstate Events in JavaScript
When the user navigates through the history using the back or forward buttons, or using keyboard shortcuts, a popstate event is fired. We can listen to this event using window.addEventListener('popstate', handler), where handler is a function that will be executed when the event occurs. The popstate event object has a state property that contains the state object of the history entry that the user navigated to. We can use this property to update our page content or perform some actions based on the state object.
However, the popstate event is only triggered by user-initiated navigation, not by pushState or replaceState. Therefore, we may want to call our handler function manually after using pushState or replaceState to update our page content accordingly. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Define a handler function function popStateHandler(event) { var state = event.state; if (state) { alert("We are on the " + state.page + " page."); } else { alert("Welcome to the home page."); } } // Listen to popstate events window.addEventListener('popstate', popStateHandler); // Push a new state object and URL to the history stack history.pushState({page: "contact"}, "Contact", "/contact"); // Call the handler function manually popStateHandler({state: {page: "contact"}}); |
That’s all about updating the URL in the address bar without reloading the current page using JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)