Window, Location and History

Updated · 7 min read
mediumES2026javascriptbrowserlocationhistoryurl

Besides the DOM, the browser gives JavaScript a set of objects for the browser window itself, together called the BOM (Browser Object Model). window is the global object and represents the tab; location is the current address; history is the tab's back and forward list; navigator describes the browser and device; screen describes the display. With URL, URLSearchParams and history.pushState, you can read and change the address without reloading the page, which is how single-page applications work.

In One Minute

  • window is the global object in a browser page; globalThis === window.
  • innerWidth/innerHeight give the viewport size; matchMedia(query) tests CSS media queries.
  • location.href, pathname, search, hash read the address; location.assign(url) navigates.
  • Parse and build URLs with new URL(...) and URLSearchParams, never with string slicing.
  • history.pushState(state, "", url) changes the address without reloading; popstate fires on Back and Forward.

The window Object

window represents the browser tab. It is the global object of a page: global functions like setTimeout and alert are its methods, and var declarations at the top of a classic script become its properties.

Property or methodMeaning
innerWidth, innerHeightViewport size in CSS pixels (including scrollbars)
outerWidth, outerHeightThe whole browser window
scrollX, scrollYHow far the page is scrolled
scrollTo(options), scrollBy(options)Scroll the page, for example { top: 0, behavior: "smooth" }
matchMedia(query)Test a CSS media query
devicePixelRatioPhysical pixels per CSS pixel (2 on most phones and Retina screens)
open(url), close()Open or close windows (popups are often blocked)
window.html
<script>
  console.log(window === globalThis);
  console.log(typeof window.setTimeout === "function");
  console.log(innerWidth > 0 && innerHeight > 0);

  const wide = matchMedia("(min-width: 768px)");
  console.log("wide layout:", wide.matches);
  wide.addEventListener("change", (e) => console.log("now wide:", e.matches));
</script>
Output
true
true
true
wide layout: true

matchMedia uses the same media queries as CSS, and its change event fires when the answer changes (for example when a phone rotates). Prefer it to listening for every resize event. The checker's browser window is wider than 768 pixels.

location and URLs

location describes the current address and can navigate to another:

PropertyFor https://www.example.com:8080/fees/report?grade=9&term=fall#totals
hrefThe whole URL
protocol"https:"
host"www.example.com:8080"
hostname"www.example.com"
port"8080"
pathname"/fees/report"
search"?grade=9&term=fall"
hash"#totals"
origin"https://www.example.com:8080"
MethodDoes
location.assign(url) (or location.href = url)Navigate, adding a history entry
location.replace(url)Navigate, replacing the current entry (Back skips it)
location.reload()Reload the page

Parsing URLs with URL and URLSearchParams

The URL class parses any URL into its parts and keeps them consistent when you change one. URLSearchParams handles the query string, including encoding:

url.js▶ Try it
const url = new URL("https://www.example.com/fees/report?grade=9&term=fall#totals");
 
console.log(url.pathname, url.hash);
console.log(url.searchParams.get("grade"), url.searchParams.get("missing"));
 
url.searchParams.set("term", "spring");
url.searchParams.append("student", "Navika Anamaneni");
console.log(url.href);
 
const relative = new URL("../help?topic=late fees", "https://www.example.com/fees/report");
console.log(relative.href);
 
const params = new URLSearchParams({ name: "Zoë & Co", grade: "9" });
console.log(params.toString());
console.log(Object.fromEntries(new URLSearchParams("a=1&b=two")));
Output
/fees/report #totals
9 null
https://www.example.com/fees/report?grade=9&term=spring&student=Navika+Anamaneni#totals
https://www.example.com/help?topic=late%20fees
name=Zo%C3%AB+%26+Co&grade=9
{ a: '1', b: 'two' }

Explanation: searchParams reads and edits the query string; the href updates automatically, with spaces encoded as +. The two-argument form resolves a relative URL against a base. URLSearchParams encodes special characters (ë, &, spaces) correctly, which hand-built strings often get wrong. URL and URLSearchParams exist in Node.js too, so this example runs anywhere.

history and Single-Page Apps

history gives access to the tab's session history. back(), forward() and go(n) move through it. The important part for modern apps is pushState, which changes the address bar and adds a history entry without loading a new page:

history.html
<button id="to-report">Report</button>
<button id="to-settings">Settings</button>
<p id="view">Home</p>
<script>
  const view = document.querySelector("#view");
  function show(page) {
    view.textContent = page;
    console.log(`showing ${page} at ${location.pathname}`);
  }

  for (const [id, page] of [["to-report", "Report"], ["to-settings", "Settings"]]) {
    document.getElementById(id).addEventListener("click", () => {
      history.pushState({ page }, "", `/${page.toLowerCase()}`);
      show(page);
    });
  }

  window.addEventListener("popstate", (event) => show(event.state?.page ?? "Home"));

  document.querySelector("#to-settings").addEventListener("click", () => {
    setTimeout(() => history.back(), 0);
  });
</script>
Output
showing Report at /report
showing Settings at /settings
showing Report at /report

Explanation: each click calls pushState, which changes location.pathname and adds an entry, then updates the page itself. When the script calls history.back() (as the Back button would), the browser fires popstate with the saved state object, and the page shows the previous view. No page loads happened at all.

Method or eventDoes
history.pushState(state, "", url)Add an entry and change the URL, no reload
history.replaceState(state, "", url)Change the current entry's URL and state, no new entry
popstate eventFires when the user (or code) moves through history
history.stateThe current entry's state object

Newer browsers also offer the Navigation API (navigation.navigate(), the navigate event), which simplifies routing; check "navigation" in window before relying on it. Frameworks' routers handle these details for you.

PropertyMeaning
navigator.language, navigator.languagesThe reader's preferred languages, like "en-US"
navigator.onLineWhether the browser thinks it is online (online/offline events report changes)
navigator.clipboard, navigator.geolocation, navigator.shareEntry points to device APIs (next lessons)
navigator.userAgentA browser identification string (unreliable; avoid sniffing it)
screen.width, screen.heightThe display size
navigator.html
<script>
  console.log(navigator.language);
  console.log(typeof navigator.onLine);
  console.log("clipboard" in navigator, "geolocation" in navigator);
  console.log(screen.width > 0);
</script>
Output
en-US
boolean
true true
true

In Practice

The Fee Tracker keeps its filters in the URL, so a filtered view can be bookmarked, shared and restored with Back, using URLSearchParams and replaceState:

filters.html
<button id="grade9">Grade 9</button>
<button id="unpaid">Unpaid only</button>
<script>
  function setFilter(key, value) {
    const url = new URL(location.href);
    url.searchParams.set(key, value);
    history.replaceState(null, "", url);
    const filters = Object.fromEntries(url.searchParams);
    console.log(location.search, JSON.stringify(filters));
  }
  document.querySelector("#grade9").addEventListener("click", () => setFilter("grade", "9"));
  document.querySelector("#unpaid").addEventListener("click", () => setFilter("status", "unpaid"));
</script>
Output
?grade=9 {"grade":"9"}
?grade=9&status=unpaid {"grade":"9","status":"unpaid"}

replaceState updates the current entry rather than adding one per click, so Back doesn't step through every filter change.

Common Mistakes

Building query strings by hand. Special characters break them. Use URLSearchParams.

Using pushState without server support. Reloading the new URL returns 404 unless the server serves the app.

Listening to every resize for layout changes. Use CSS, or matchMedia and its change event.

Sniffing navigator.userAgent. Test for the feature you need.

Practice

Challenge: Write withParam(urlString, key, value) that returns the URL string with the parameter set (replacing any existing value), and test it with a value containing & and a space.

Show solution
with-param.js▶ Try it
function withParam(urlString, key, value) {
  const url = new URL(urlString);
  url.searchParams.set(key, value);
  return url.href;
}
 
console.log(withParam("https://www.example.com/fees?grade=9", "grade", "10"));
console.log(withParam("https://www.example.com/fees", "q", "late & unpaid"));
Output
https://www.example.com/fees?grade=10
https://www.example.com/fees?q=late+%26+unpaid

Quick check: Window, location and history

3 questions
1Which part of https://example.com/fees?grade=9#top is location.search?
2What does history.pushState(state, "", "/report") do?
3Why use URLSearchParams instead of joining strings?

Key Takeaways

TaskCode
Viewport widthinnerWidth
Media querymatchMedia("(min-width: 768px)").matches
Read a query parameternew URL(location.href).searchParams.get("grade")
Navigatelocation.assign("/fees")
Change URL without reloadhistory.pushState(state, "", "/report")
Handle BackaddEventListener("popstate", ...)

Was this tutorial helpful?

Lesson 78 of 139