Course contentsShow
← Web Development
Lesson 965 of 2,98217. URL and History ManagementFree lesson

Updating the URL with pushState and replaceState

How the URL parameter changes the address bar while staying on the same origin.

Updating the URL with pushState and replaceState

You'll learn: How pushState and replaceState change the browser's address bar without reloading the page or navigating away.

How It Works

Both pushState and replaceState accept a URL parameter (the third argument) that directly updates what you see in the browser's address bar. This is powerful: you can create the illusion of "navigation" to different pages without actually leaving the current document.

The catch: The new URL must have the same origin (protocol, domain, and port) as your current page. You can't use these methods to change example.com to another-site.com — that's a security restriction.

What You Can Change

Within your origin, you're free to modify:

  • Path: /home → /about
  • Query string: ?page=1 → ?page=2
  • Hash: #section1 → #section2

For example:

// Changes address bar from /home to /products
history.pushState(null, '', '/products');

// Changes query string from ?id=5 to ?id=10
history.replaceState(null, '', '?id=10');

Notice the URL in your browser updates instantly — but the page doesn't reload, no network request fires, and your JavaScript keeps running.

Why This Matters

Think of it like updating a book's bookmark without closing the book. The address bar reflects where the user "is" conceptually, making URLs shareable and bookmarkable. When someone copies that URL, they can return to that exact view later (assuming your code reads the URL on load and restores the state).

The same-origin requirement ensures you can't spoof addresses from other websites, keeping the web secure.

Key Takeaway: pushState and replaceState change the browser's address bar to any URL within your origin, updating the location without navigation or page reloads.