What is the Location API?

window.location represents the current page's URL: you can read its parts (protocol, host, path, query, hash) and change it to navigate, reload or redirect.

Reading the URL

  • location.href: the full URL.
  • location.origin: protocol + host + port.
  • location.pathname: /products/42.
  • location.search: ?sort=price&page=2. Parse it with URLSearchParams.
  • location.hash: #reviews.
  • location.host, hostname, port, protocol.

Navigating

  • location.assign(url) or location.href = url: navigate and add a history entry.
  • location.replace(url): navigate and replace the current entry, so Back does not return to it. Use it for redirects such as after login.
  • location.reload(): reload the page.
  • Setting location.hash jumps to an anchor without reloading and fires hashchange.

Location vs History API

Changing location (except the hash) loads a new page. The History API changes the URL without loading anything, for single-page apps.

Working with URLs

The URL class parses and builds URLs safely: new URL(path, location.origin), url.searchParams.set("page", "2"). Avoid concatenating query strings by hand; URLSearchParams handles encoding.

Security

Never redirect to a URL taken directly from user input or a query parameter (?next=...) without validating it: open redirects are used in phishing. Allow only same-origin or known destinations.

Code example

js
1console.log(location.origin, location.pathname);
2
3// Parse and build URLs safely instead of string concatenation
4const url = new URL("https://shop.example.com/products?category=books&sort=price#reviews");
5console.log(url.hostname, url.pathname, url.hash); // shop.example.com /products #reviews
6
7const params = url.searchParams;
8console.log(params.get("category"), params.has("sort")); // books true
9params.set("page", "2");
10params.set("q", "café & tea"); // encoded for you
11params.delete("sort");
12console.log(url.search); // ?category=books&page=2&q=caf%C3%A9+%26+tea
13
14// Read the current page's query string
15const current = new URLSearchParams(location.search);
16console.log(Object.fromEntries(current)); // whatever params this page has
17
18// Validate redirect targets (prevent open redirects)
19function safeRedirectTarget(next, fallback = "/") {
20 try {
21 const target = new URL(next, location.origin);
22 return target.origin === location.origin ? target.pathname + target.search : fallback;
23 } catch {
24 return fallback;
25 }
26}
27console.log(safeRedirectTarget("/dashboard?tab=2")); // /dashboard?tab=2
28console.log(safeRedirectTarget("https://evil.example/phish")); // /
29
30// Navigation (commented out so the example doesn't leave the page):
31// location.assign("/login"); // adds a history entry
32// location.replace("/login"); // replaces the current entry

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app