Understanding the URL and History in JavaScript
In modern single-page applications (SPAs), it's common to update the URL or manipulate the browser history without refreshing the page. JavaScript offers the window.location
and history
APIs to handle this.
Reading URL Parts using window.location
You can access different parts of the current URL using window.location
.
console.log("Full URL:", window.location.href);
console.log("Protocol:", window.location.protocol);
console.log("Host:", window.location.host);
console.log("Pathname:", window.location.pathname);
console.log("Search Params:", window.location.search);
console.log("Hash:", window.location.hash);
Output:
Full URL: https://example.com/products?item=42#details Protocol: https: Host: example.com Pathname: /products Search Params: ?item=42 Hash: #details
Updating the URL without Reload - history.pushState()
The pushState()
method allows you to update the browser’s address bar without reloading the page.
history.pushState({ page: 1 }, "Title 1", "/page1");
console.log(window.location.href);
Output:
https://yourdomain.com/page1
What's in the pushState()
parameters?
stateObject
: A JavaScript object associated with the new history entry.title
: Not widely used, but required for compatibility.url
: The new URL you want to appear in the address bar.
Replacing the Current URL - history.replaceState()
If you want to change the URL without adding a new entry to the history stack, use replaceState()
.
history.replaceState({ page: 2 }, "Title 2", "/page2");
console.log(window.location.href);
Output:
https://yourdomain.com/page2
Q: Can I go back after replaceState()
?
A: No. Since replaceState()
doesn’t add a new entry, there's no previous page to return to using the back button.
Navigating History - back()
, forward()
, and go()
history.back(); // Simulates browser back button
history.forward(); // Simulates browser forward button
history.go(-1); // One step back
history.go(1); // One step forward
Q: When should I use pushState
instead of location.href
?
A: Use pushState()
when you want to update the URL without reloading the page — especially useful in SPAs.
Bonus Tip: Listen to Popstate Events
To detect when the user navigates using the browser back/forward buttons:
window.addEventListener('popstate', function(event) {
console.log("Location changed!", event.state);
});
Summary
location
lets you read and manipulate the full URL.pushState()
adds a new URL to history without reloading.replaceState()
modifies the current history entry.back()
,forward()
, andgo()
help navigate history programmatically.
Practice Questions
Q1: How can you update the URL without causing a page reload?
A1: Use history.pushState()
or history.replaceState()
.
Q2: What’s the difference between pushState()
and replaceState()
?
A2: pushState()
adds a new entry; replaceState()
modifies the current one.