JS Location
window.location describes the page's URL and lets you navigate. The shape mirrors a parsed URL.
Parts
| Property | For https://app.io:8080/path?x=1#top |
|---|---|
href | The whole string. Writable — assigning navigates. |
origin | "https://app.io:8080" |
protocol | "https:" |
host | "app.io:8080" |
hostname | "app.io" |
port | "8080" |
pathname | "/path" |
search | "?x=1" |
hash | "#top" |
Navigation methods
JS
location.assign("/profile"); // navigate, adds history entry
location.replace("/profile"); // navigate WITHOUT history entry
location.reload(); // reload current page
location.reload(true); // (legacy) force reload from server
Read & modify query parameters
JS
// Modern way — URLSearchParams
const params = new URLSearchParams(location.search);
params.get("token");
params.set("page", 2);
location.search = params.toString(); // navigates with new query
// Full URL parsing
const url = new URL(location.href);
url.searchParams.set("ref", "header");
history.replaceState(null, "", url); // update bar without reload
Tip: Use
URL + URLSearchParams over manual string concat. They handle encoding, edge cases (no ?, repeated keys), and are easier to read.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS Location!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Reload the current page.
location.
();
Six letters.
Discussion
Loading…