Audio, Location and History: Web Audio, URLs, the History API and the Navigation API
Play and synthesize sound with Audio and the Web Audio API, read and change the URL with location, keep Back and Forward working in single-page apps with hashchange, pushState and popstate, structured clone, and the Navigation API that became Baseline in 2026.
kvi5hnuCode Sprout team member8 min readOn this page
This article covers two groups of browser APIs from the same part of the platform: sound, from simple playback to synthesized audio, and the URL and history of a tab, which single-page applications must manage themselves so that links, bookmarks and the Back button keep working.
Playing sounds with Audio
An <audio> element doesn't need to be in the document to play. The Audio constructor creates one directly:
const click = new Audio("/sounds/click.mp3"); // starts loading immediately
button.addEventListener("click", async () => {
const sound = click.cloneNode(); // a fresh copy, so rapid clicks can overlap
sound.volume = 0.6;
try {
await sound.play();
} catch (err) {
console.warn("Playback blocked:", err.name); // usually NotAllowedError
}
});
Things to know:
play()returns a promise. Browsers enforce autoplay policies: audible playback that isn't triggered by a user gesture, such as a click or key press, is usually rejected with aNotAllowedError. Start sound from event handlers.- Media elements share a rich API with
<video>:pause(),currentTime,duration,loop,playbackRate,muted, and events likecanplaythrough,timeupdateandended. cloneNode()creates a separate element for the same file (the data is usually cached), which lets the same short sound play several times at once.
Synthesizing sound with the Web Audio API
For games, music apps and visualizations, the Web Audio API builds a graph of audio nodes, much like patching cables between the modules of a synthesizer. Sources (oscillators, decoded files, microphones) flow through processing nodes (gain, filters, panners, analyzers) to context.destination, the speakers:
const audio = new AudioContext();
function playChord(frequencies = [261.63, 329.63, 392.0], duration = 1.5) {
const now = audio.currentTime; // seconds on the audio clock
const volume = audio.createGain();
volume.gain.setValueAtTime(0.3, now);
volume.gain.exponentialRampToValueAtTime(0.001, now + duration); // fade out
volume.connect(audio.destination);
for (const frequency of frequencies) { // C major: C4, E4, G4
const oscillator = audio.createOscillator();
oscillator.type = "triangle";
oscillator.frequency.value = frequency;
oscillator.connect(volume);
oscillator.start(now);
oscillator.stop(now + duration);
}
}
playButton.addEventListener("click", async () => {
if (audio.state === "suspended") await audio.resume(); // also subject to autoplay rules
playChord();
});
Each node is used once, and connect() wires the graph. AudioParam methods (setValueAtTime, linearRampToValueAtTime, exponentialRampToValueAtTime) schedule changes precisely on the audio clock, which is far more accurate than timers. To play files through the graph, fetch them, decode them with audio.decodeAudioData(arrayBuffer), and play them through an AudioBufferSourceNode. An AnalyserNode provides the frequency data that drives visualizers.
The current URL: location
window.location (also document.location) is a Location object describing the current page's URL. It has the same parts as a URL object (article 88):
const location = new URL("https://shop.example:8443/teas/list?q=oolong&n=20#top");
console.log(location.protocol, location.hostname, location.port, location.pathname);
console.log(location.search, location.hash, location.origin);
console.log(location.searchParams.get("q"), Number(location.searchParams.get("n")));
https: shop.example 8443 /teas/list
?q=oolong&n=20 #top https://shop.example:8443
oolong 20
Location has no searchParams of its own, so in a browser, parse the query with new URL(location.href).searchParams or new URLSearchParams(location.search). document.URL is the same address as a plain string.
Loading a different page
location.href = "/checkout"; // navigate; the current page stays in history
location.assign("/checkout"); // same thing
location.replace("/login"); // navigate, replacing the current history entry
location.reload(); // reload the current page
location.search = "?q=green"; // changing a part also navigates
location.hash = "#reviews"; // only the fragment: scrolls, no reload
replace() is the right choice for redirects, such as sending a logged-out user to the login page, because the Back button then skips the page that redirected instead of bouncing the user forward again.
Single-page apps and history
In a single-page application (SPA), JavaScript renders new "pages" without loading new documents. For this to feel like normal browsing, each view needs its own URL, and Back and Forward must move between views. The browser keeps a session history for each tab: a list of entries with a current position. There are three generations of APIs for working with it.
hashchange
The oldest technique encodes the app's state in the fragment (#/teas/green). Setting location.hash adds a history entry without reloading, and every change, whether made by your code or by Back and Forward, fires hashchange on window:
window.addEventListener("hashchange", () => render(location.hash.slice(1) || "/"));
render(location.hash.slice(1) || "/"); // initial view
link.addEventListener("click", () => { location.hash = "/teas/green"; }); // render() runs via hashchange
It works everywhere, and servers never see the fragment. The URLs are less clean, though, and the fragment can't also be used for its normal job of scrolling to an element.
pushState, replaceState and popstate
The History API lets you add entries with real paths:
history.pushState(state, "", url)adds a new entry after the current one (discarding any forward entries) and changes the URL bar, without loading anything or firing an event.history.replaceState(state, "", url)changes the current entry instead of adding one.- When the user moves between entries (Back, Forward, or
history.back(),forward(),go(n)), the browser firespopstateonwindow, andevent.stateholds a copy of the state saved with that entry.
The middle argument is an unused legacy title; pass "". The URL must be same-origin.

The usual design keeps the URL as the source of truth, because a bookmarked or shared link arrives without any saved state. A pair of functions converts between state and URL:
const DEFAULTS = { category: "all", sort: "popular", page: 1 };
function stateToURL(state, base) {
const url = new URL(base);
url.search = ""; // rebuild the query from scratch
for (const [key, value] of Object.entries(state)) {
if (value !== DEFAULTS[key]) url.searchParams.set(key, value); // keep URLs short
}
return url.href;
}
function stateFromURL(href) {
const params = new URL(href).searchParams;
const page = Number.parseInt(params.get("page") ?? "", 10);
return {
category: params.get("category") ?? DEFAULTS.category,
sort: ["popular", "price", "new"].includes(params.get("sort")) ? params.get("sort") : DEFAULTS.sort,
page: Number.isInteger(page) && page > 0 ? page : DEFAULTS.page,
};
}
const base = "https://shop.example/teas?utm=mail#reviews";
const href = stateToURL({ category: "green tea", sort: "price", page: 1 }, base);
console.log(href);
console.log(stateFromURL(href));
console.log(stateFromURL("https://shop.example/teas?sort=hacked&page=-4"));
https://shop.example/teas?category=green+tea&sort=price#reviews
{ category: 'green tea', sort: 'price', page: 1 }
{ category: 'all', sort: 'popular', page: 1 }
URL input comes from users, so stateFromURL validates everything and falls back to defaults. Wiring it to the History API:
function show(state) { /* render products for this state */ }
function go(state) { // called when the user changes a filter
history.pushState(state, "", stateToURL(state, location.href));
show(state);
}
window.addEventListener("popstate", (event) => {
show(event.state ?? stateFromURL(location.href)); // Back/Forward
});
const initial = stateFromURL(location.href); // first load, bookmark or refresh
history.replaceState(initial, "", location.href); // give the first entry a state too
show(initial);
Two more things are needed in practice. Links must be intercepted: a click handler (or event delegation, article 108) calls preventDefault() on internal links and uses go(). And the server must return the app's HTML for every path the app creates, so that reloading /teas?category=green works.
The structured clone algorithm
State objects aren't stored with JSON.stringify. The browser copies them with the structured clone algorithm, the same one used by postMessage (article 120), IndexedDB (article 119) and the global structuredClone() function. It handles more types than JSON, but not everything:
class Filter {
constructor(tag) { this.tag = tag; }
describe() { return `tag ${this.tag}`; }
}
const state = {
when: new Date(Date.UTC(2026, 0, 15)),
tags: new Set(["green", "loose"]),
prices: new Map([["min", 5], ["max", 20]]),
filter: new Filter("organic"),
};
state.self = state; // a cycle
const copy = structuredClone(state);
console.log(copy.when instanceof Date, copy.tags.has("green"), copy.prices.get("max"));
console.log(copy.self === copy, copy === state);
console.log(copy.filter instanceof Filter, copy.filter);
try {
structuredClone({ onClick() {} });
} catch (err) {
console.log(err.name);
}
try {
JSON.stringify(state);
} catch (err) {
console.log("JSON:", err.name);
}
true true 20
true false
false { tag: 'organic' }
DataCloneError
JSON: TypeError
Dates, Maps, Sets, typed arrays, RegExps, errors and cycles survive. Class instances come back as plain objects: prototypes, getters and methods are lost. Functions and DOM nodes throw a DataCloneError. Keep history state small and plain, and rebuild class instances from it when needed.
The Navigation API
The History API has well-known gaps: pushState fires no event, you can't see the list of entries, and every app must intercept link clicks and form submissions itself. The Navigation API (window.navigation) was designed for SPAs to fix these gaps. It shipped in Chromium browsers in 2022 and reached Firefox 147 and Safari 26.2 in late 2025 and early 2026, making it Baseline across all major browsers in January 2026.
Its centerpiece is one navigate event that fires for every same-document or cross-document navigation the page can handle: link clicks, form submissions, location changes, Back and Forward, and the API's own navigation.navigate(). You decide whether to intercept it and render it yourself:
navigation.addEventListener("navigate", (event) => {
if (!event.canIntercept || event.hashChange || event.downloadRequest !== null) return;
const url = new URL(event.destination.url);
if (!url.pathname.startsWith("/teas")) return; // let the browser load other pages normally
event.intercept({
async handler() {
const state = stateFromURL(url.href);
const products = await fetchProducts(state, { signal: event.signal }); // aborted if the user navigates again
renderProducts(products);
},
});
});
intercept() turns the navigation into a same-document one: the URL updates and a history entry is created as normal, the browser shows its loading indicator while the handler's promise is pending, and focus and scroll position are handled sensibly afterwards. navigatesuccess and navigateerror events report the outcome. event.navigationType says whether the navigation is a "push", "replace", "reload" or "traverse" (Back/Forward).
Other parts of the API:
await navigation.navigate("/teas?category=green", { state: { from: "menu" } }).finished;
navigation.currentEntry.getState(); // { from: "menu" }
navigation.entries().map((entry) => entry.url); // this app's same-origin history entries
navigation.canGoBack; // instead of guessing from history.length
await navigation.back().finished;
navigation.updateCurrentEntry({ state: { scroll: 420 } });
For new SPA routing code, the Navigation API is simpler and more robust than pushState with click interception. Framework routers still use the History API where they need to support older browsers, and the two coexist: History API changes also appear as Navigation API entries.
Common questions
Why doesn't popstate fire when I call pushState?
By design: pushState and replaceState only change the history list and the URL. Render the new view yourself right after calling them. popstate is only for moving between existing entries.
Why did my sound not play on page load?
Autoplay policies block audible playback without a user gesture. play() rejects with NotAllowedError, and an AudioContext starts suspended. Start audio from a click or key handler, or play muted.
location.href or location.replace for redirects?
Use replace() when the current page shouldn't stay in history, such as after a redirect or login. Use href or assign() for normal navigation, so the user can come back.
Should I use the History API or the Navigation API?
For new code targeting current browsers, the Navigation API: one navigate event covers links, forms and Back/Forward, with built-in abort signals and loading state. Keep the History API approach for code that must run in browsers older than 2026 releases.
Summary
new Audio(url)plays sound files;play()returns a promise and is subject to autoplay rules. The Web Audio API connects source, processing and destination nodes and schedules changes on its own precise clock.locationexposes URL parts;assign/hrefnavigate,replacenavigates without leaving a history entry,reloadreloads. Parse queries withURL/URLSearchParams.- SPAs keep history in sync with
hashchange, or withpushState/replaceStatepluspopstate. Keep the URL as the source of truth, and validate it. - History state is copied with structured clone: Maps, Sets, Dates and cycles survive; class prototypes don't; functions and DOM nodes throw.
- The Navigation API's
navigateevent andintercept()handle every navigation in one place. It's Baseline since January 2026.
Practice Questions
After pushState(a), pushState(b), history.back(), pushState(c), which entries can the user reach with Forward from c, and which entries exist?
Answer
No forward entries exist, because pushState(c) discarded b. The list is: the original page, a, c, with c current.
Why should a router read location.href on startup instead of relying on history.state?
Answer
A bookmarked, shared or freshly typed URL has no saved state, so history.state is null on that first load. The URL must contain everything needed to rebuild the view.
What does structuredClone(new Map([["k", new Date(0)]])) return?
Answer
A new Map with key "k" and a new Date with the same time. Structured clone preserves Maps and Dates, unlike JSON.
Write a Navigation API listener that intercepts navigations to /docs/... and renders them with renderDoc(path).
Answer
navigation.addEventListener("navigate", (event) => {
const url = new URL(event.destination.url);
if (!event.canIntercept || event.hashChange || !url.pathname.startsWith("/docs/")) return;
event.intercept({ handler: () => renderDoc(url.pathname) });
});
Previous: Drawing with Canvas: Paths, Styles, Text, Images, Transforms, Clipping and Pixels
Next: Networking with fetch: Requests, Responses, Errors, Streaming, Uploads and Cancellation

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.