Skip to content
Tutorials Center
My learning

Topics

Lesson 93 of 122 ยท Web APIs

History, Location and URL APIs

Read and change the address bar from JavaScript. Learn the URL and URLSearchParams classes, the location object, pushState and popstate, and hash-based routing.

The address bar is part of your app's user interface. It decides what happens when someone copies a link, presses the back button or reloads the page. Single-page apps, filter panels, tabbed views and image galleries all feel better when they keep the URL in step with what is on screen, so that "this exact view" can be bookmarked and shared.

Browsers expose the address bar through three related tools. The URL classes (URL and URLSearchParams) take addresses apart and build them safely. The location object reads the current address and navigates. The History API adds and replaces entries in the back/forward list without a page load. This lesson walks through each one and then combines them into a tiny router.

Anatomy of a URL

A URL is made of named parts:

TEXT
https://shop.example.com:8443/products/shoes?color=red&size=42#reviews
\___/   \_______________/\__/\____________/ \______________/ \_____/
scheme       hostname    port   pathname        search         hash

The URL class parses a string and gives you each part as a property. It also throws a TypeError for invalid input, which makes it a better validator than a regular expression.

Take a URL apart

Pass a second argument to resolve a relative address: new URL("../cart", "https://shop.example.com/products/shoes") gives https://shop.example.com/cart. All the properties are writable, so url.pathname = "/sale" changes just that part, and url.href (or String(url)) gives you the finished string.

URLSearchParams: the query string

Building query strings by hand is a classic bug source: forgetting to encode & or a space breaks the request. URLSearchParams does the encoding for you (see also URL Encoding).

JavaScript
const params = new URLSearchParams({ q: "red shoes & socks", page: 2 });
params.append("tag", "sale");
params.append("tag", "new");        // repeated keys are allowed

params.toString();   // "q=red+shoes+%26+socks&page=2&tag=sale&tag=new"
params.get("q");     // "red shoes & socks"
params.getAll("tag"); // ["sale", "new"]
params.has("page");  // true
params.delete("page");

url.searchParams is a live URLSearchParams linked to a URL: change it and url.search updates.

Build and read a query string

new FormData(form) produces [name, value] pairs, and Object.fromEntries() turns the pairs back into an object. When a key can repeat, use getAll() instead.

The location object

window.location is a live URL-like object for the current page. You can read the same parts (location.pathname, location.search, location.hash) and navigate:

Code Effect
location.href = "/pricing" Navigate to a new page; adds a history entry
location.assign(url) Same as setting href
location.replace(url) Navigate without adding a history entry (the back button skips this page)
location.reload() Reload the current page
location.hash = "#faq" Change only the fragment: no page load, but a new history entry

Setting location.hash is the simplest way to change the URL without loading anything, and it fires a hashchange event. That makes it a good base for a small router.

Never assign untrusted input to location.href. A value like javascript:... can run code. Validate redirects against a list of allowed paths, or build them with new URL(input, location.origin) and check that url.origin === location.origin.

Hash routing

A hash router shows different content depending on location.hash, and works even on a plain static file. Each "page" is a section the script reveals.

A tiny hash router

Click the links, then use the preview's own history if your browser offers it: the hash changes, hashchange fires, and render() redraws. Because the part after # is never sent to a server, hash routes need no server configuration. Their downside is that the URLs look dated and search engines treat them as the same page.

The History API

The History API lets a script add or change history entries with ordinary-looking paths, so a single-page app can have URLs like /products/shoes with no reload.

JavaScript
history.pushState(state, "", "/products/shoes");   // add an entry
history.replaceState(state, "", "/products/shoes?color=red"); // edit the current one
history.back();       // like the back button
history.forward();
history.go(-2);       // two entries back
  • state is any structured-cloneable value saved with the entry and returned later as history.state.
  • The second argument is ignored by browsers; pass "".
  • The URL must be on the same origin, otherwise the call throws a SecurityError.
  • pushState does not load anything and does not fire an event. Your code updates the view itself.

When the user presses back or forward, the browser fires popstate on window with the saved state:

JavaScript
function go(path) {
  history.pushState({ path }, "", path);
  render(path);
}

window.addEventListener("popstate", (event) => {
  render(location.pathname); // draw whatever the URL now says
});

document.addEventListener("click", (event) => {
  const link = event.target.closest("a[data-link]");
  if (!link) return;
  event.preventDefault();   // stop the real navigation
  go(link.getAttribute("href"));
});

Two rules keep this reliable. First, render from the URL: both your click handler and popstate should end in the same render() that reads location, so reloads, back and forward all agree. Second, the server must answer every path you create. If someone reloads /products/shoes, the server receives a request for that path, so it has to serve your app for it, or the visitor sees a 404.

Why the examples here use hashes

The sandboxed preview you edit in this site runs in an opaque origin, where pushState with a path is blocked. This snippet shows how to cope, and it will usually print the "blocked" branch here:

pushState and the sandbox

On your own page served from a real origin, the same code works. Which message you see depends on the browser and the sandbox, and the try/catch makes the page robust either way.

Scroll restoration

When a user goes back, browsers try to restore the scroll position. In an app that renders content asynchronously, that can happen before the content exists. You can take over with history.scrollRestoration = "manual" and store the scroll offset in history.state yourself. Leave it on "auto" unless you have measured a problem.

Choosing an approach

Need Tool
Read or build query strings URL and URLSearchParams
Simple navigation or redirect location.assign() / location.replace()
Routing without server setup Hash routing (hashchange)
Clean paths in a single-page app pushState + popstate + server fallback
Update filters without extra history entries replaceState

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why prefer URLSearchParams over concatenating a query string by hand?

    URLSearchParams percent-encodes keys and values, which avoids broken or injectable query strings.
  2. 2. What is the difference between location.assign() and location.replace()?

    Both navigate. location.replace() overwrites the current entry, which suits redirects the user should not return to.
  3. 3. Which statement about history.pushState is true?

    pushState only edits history. The URL must be same-origin, and no event fires, so your own code renders the new view.
  4. 4. When does popstate fire?

    popstate fires when the active history entry changes through navigation, not when your code calls pushState or replaceState.
  5. 5. A visitor reloads /products/shoes in your pushState-based app and sees a 404. What is missing?

    Reloading sends a real request for that path. The server must return your app (a fallback route) for every path the client router can create.

Summary

  • URL splits an address into origin, pathname, search, hash and more, and throws on invalid input.
  • URLSearchParams builds, reads and encodes query strings; url.searchParams stays linked to the URL.
  • location reads the current address; assign, replace and reload navigate, and changing hash is a cheap way to alter the URL without loading.
  • pushState, replaceState and popstate give you clean URLs in a single-page app; always render from the URL and make the server answer every route.
  • Validate any URL you redirect to, and expect pushState to be blocked inside sandboxed previews.

Next lesson: Cross-Origin Requests and CORS, where you learn why browsers sometimes refuse to let one site read another's responses.