How do I modify the URL without reloading the page?
Modifying the URL without reloading the page can be achieved using the History API provided by HTML5. It includes the and methods, as well as the event. These methods allow us to add, modify, or delete entries in the browsing history without triggering a page reload.Using pushState to Modify the URLThe method adds a new state to the browsing history. This state is accessible via the back and forward buttons. The method accepts three parameters: a state object, a title (which is currently not supported by most browsers and is typically passed as or an empty string), and a new URL.In the above example, the current URL is changed to "/another-page.html". The URL is updated in the address bar, but the page does not reload. Additionally, a new entry is added to the history stack, allowing users to navigate back to the previous state using the back button.Using replaceState to Modify the URLIf you simply want to modify the current history entry without adding a new one, use the method.This replaces the current history entry and updates the browser's address bar with the new URL without adding a new history entry. As a result, when users click the back button, they will not see the replaced URL.Listening to the popstate EventYou can respond to URL changes when users click the back or forward buttons by listening to the event.The event is triggered whenever the active history entry changes. At this point, you can use to access the state object set by or methods.Example ScenarioSuppose you are developing a SPA (Single Page Application) and you want the URL to reflect the current view or state when users navigate to different content, without reloading the page. You can combine AJAX to fetch content with to update the URL. This way, even if users refresh the page, the correct content is loaded based on the URL, while maintaining consistent navigation history.For example, assume a user clicks a link from the homepage to a blog article:In this example, when the user clicks the link, we use AJAX to asynchronously fetch the article content and update the content display area. Then, we use to update the URL, reflecting the new content the user sees. The URL in the address bar changes, and users can navigate using the browser's back and forward buttons, but the page is never reloaded.