How do I modify the URL without reloading the page using JavaScript?

How do I modify the URL without reloading the page using JavaScript?
----------------------------------------------

In JavaScript, you can modify the URL without reloading the page using the History API. Specifically, you can use the pushState() method to update the URL without triggering a full page refresh.

The pushState() method allows you to add or modify history entries and change the URL associated with the current document without actually reloading the page. Here's an example:

// New URL state
const newURL = '/new-page';

// Change the URL without reloading the page
history.pushState(null, null, newURL);
  • The pushState() method takes three arguments:
    • state: A JavaScript object representing a state object associated with the new history entry (commonly set to null if not needed).
    • title: A string representing the title of the new history entry (usually set to null as modern browsers ignore this parameter).
    • url: A string representing the new URL you want to set.

This changes the URL displayed in the browser's address bar to the specified newURL without causing a full page reload.

However, note that while pushState() updates the URL, it doesn't trigger a server request or load new content. You'll need to handle changes in the URL and manage content updates within your JavaScript code (for instance, by listening for the popstate event to detect URL changes and dynamically updating content).

For example, to handle the back/forward navigation and update content based on the URL changes:

window.onpopstate = function(event) {
  // Handle the URL change, fetch data, or update content based on the URL
  // For instance, load content dynamically based on the URL
  console.log('URL changed:', window.location.href);
  // Perform actions or fetch data based on the updated URL
};

This onpopstate event handler will be triggered whenever the user navigates using the browser's back/forward buttons or when history.pushState() or history.replaceState() is called. You can use this event to handle content updates based on the URL changes.

Categories: Java Script Tags: #ES6, #JavaScript,

Newsletter Subcribe

Receive updates and latest news direct from our team. Simply enter your email.