Episode 1 — Fundamentals / 1.16 — Using Browser Functionalities in JavaScript
1.16.b — window.location & window.history
In one sentence:
locationis the current URL and a navigation lever;historyis the tab’s back/forward stack — and the History API (pushState/replaceState) lets SPAs change the URL without a full document reload.
Navigation: ← 1.16.a — BOM · 1.16.c — Storage & Cookies →
1. window.location (the Location object)
Useful parts of a URL
| Property | Example (https://ex.com/app?id=1#sec) |
|---|---|
href | Full URL string |
protocol | "https:" |
host | "ex.com" (hostname + port if any) |
hostname | "ex.com" |
pathname | "/app" |
search | "?id=1" |
hash | "#sec" |
2. Navigation with location
// Assigning href navigates (like clicking a link) — adds history entry by default
window.location.href = "https://example.com";
// Replace current entry (user cannot “Back” to previous page in some cases)
window.location.replace("https://example.com/offline.html");
// Reload (uses cache heuristics like a toolbar refresh)
window.location.reload();
For a hard reload (skip cache as much as possible), users use DevTools or browser UI — reload() has no reliable cross-browser “hard” flag in modern specs; avoid relying on deprecated boolean arguments.
location.assign(url) — like setting href. replace swaps current history entry.
3. Same-page jumps
location.hash = "section-2"; // updates hash, scrolls to id="section-2" if present
Fires hashchange (on window) when hash changes — useful for simple client-side routing.
4. window.history
| Method / property | Role |
|---|---|
history.length | Number of entries in session history (not always intuitive) |
history.back() | Like browser Back |
history.forward() | Forward |
history.go(n) | Relative jump (-1 = back) |
These respect user gesture expectations — avoid trapping users in unclosable flows (UX + security).
5. History API: pushState & replaceState
history.pushState({ page: 1 }, "", "/app/users/42");
- Updates URL and adds a history entry — no network request, no automatic scroll.
- Your app must listen for
popstateto restore UI when user clicks Back/Forward.
replaceState — same but replaces current entry (good for replacing a transient URL).
SPA routing (React Router, Vue Router, etc.) builds on these primitives plus popstate.
6. Key takeaways
locationexposes URL parts and navigation / reload methods.history.back()/forward()/go()mirror browser chrome.pushState/replaceStatechange URL without full page load — pair withpopstatefor correct UX.
Explain-It Challenge
Explain without notes:
- What is the difference between
location.assignandlocation.replace? - Why does
pushStatealone not load a new HTML document from the server? - When should an SPA listen for
popstate?
Navigation: ← 1.16.a — BOM · 1.16.c — Storage & Cookies →