Window, Location and History
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
windowis the global object in a browser page;globalThis === window.innerWidth/innerHeightgive the viewport size;matchMedia(query)tests CSS media queries.location.href,pathname,search,hashread the address;location.assign(url)navigates.- Parse and build URLs with
new URL(...)andURLSearchParams, never with string slicing. history.pushState(state, "", url)changes the address without reloading;popstatefires 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 method | Meaning |
|---|---|
innerWidth, innerHeight | Viewport size in CSS pixels (including scrollbars) |
outerWidth, outerHeight | The whole browser window |
scrollX, scrollY | How 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 |
devicePixelRatio | Physical pixels per CSS pixel (2 on most phones and Retina screens) |
open(url), close() | Open or close windows (popups are often blocked) |
<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>true
true
true
wide layout: truematchMedia 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:
| Property | For https://www.example.com:8080/fees/report?grade=9&term=fall#totals |
|---|---|
href | The 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" |
| Method | Does |
|---|---|
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:
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")));/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:
<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>showing Report at /report
showing Settings at /settings
showing Report at /reportExplanation: 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 event | Does |
|---|---|
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 event | Fires when the user (or code) moves through history |
history.state | The 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.
navigator and screen
| Property | Meaning |
|---|---|
navigator.language, navigator.languages | The reader's preferred languages, like "en-US" |
navigator.onLine | Whether the browser thinks it is online (online/offline events report changes) |
navigator.clipboard, navigator.geolocation, navigator.share | Entry points to device APIs (next lessons) |
navigator.userAgent | A browser identification string (unreliable; avoid sniffing it) |
screen.width, screen.height | The display size |
<script>
console.log(navigator.language);
console.log(typeof navigator.onLine);
console.log("clipboard" in navigator, "geolocation" in navigator);
console.log(screen.width > 0);
</script>en-US
boolean
true true
trueIn 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:
<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>?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
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"));https://www.example.com/fees?grade=10
https://www.example.com/fees?q=late+%26+unpaidKey Takeaways
| Task | Code |
|---|---|
| Viewport width | innerWidth |
| Media query | matchMedia("(min-width: 768px)").matches |
| Read a query parameter | new URL(location.href).searchParams.get("grade") |
| Navigate | location.assign("/fees") |
| Change URL without reload | history.pushState(state, "", "/report") |
| Handle Back | addEventListener("popstate", ...) |
Was this tutorial helpful?