The location object holds the address of the current page and can send the browser somewhere else. An address is made of named parts, and the same parts show up when you work with any URL in code. This lesson names the parts, reads values out of the query string, builds addresses safely, and covers the ways to navigate.
Take this address:
https://www.example.com:8080/lessons/page.html?topic=json&level=2#intro
location breaks the current page's address into properties. The built-in URL object has exactly the same properties for any address you give it, which makes it a handy way to practice:
const url = new URL("https://www.example.com:8080/lessons/page.html?topic=json&level=2#intro");
console.log(url.href);
console.log(url.protocol);
console.log(url.host);
console.log(url.hostname);
console.log(url.port);
console.log(url.origin);
console.log(url.pathname);
console.log(url.search);
console.log(url.hash);
| Property | Holds |
|---|---|
href | the whole address |
protocol | how to talk to the server, with the colon: "https:" |
host | the server name plus the port, if there is one |
hostname | the server name alone |
port | the port number as text (empty for the default) |
origin | protocol + host: who the page belongs to |
pathname | the path to the page, starting with / |
search | the query string, starting with ? |
hash | the fragment, starting with # |
For your current page, location.pathname is where you are on the site, and location.origin is the site itself.
The query string carries small pieces of information in the address, as name=value pairs joined by &. Do not split it by hand: URLSearchParams reads it correctly, including special characters.
const params = new URLSearchParams("?topic=json&level=2&tag=a&tag=b");
console.log(params.get("topic"));
console.log(params.get("level"), typeof params.get("level"));
console.log(params.get("missing"));
console.log(params.has("level"));
console.log(params.getAll("tag"));
On a real page you pass it the current query string: new URLSearchParams(location.search). The values arrive as strings, so convert with Number(...) when you need a number.
const params = new URLSearchParams("topic=json&level=2");
for (const [key, value] of params) {
console.log(key + " = " + value);
}
If you glue a query string together with +, a space or an & in the value breaks the address. Let URLSearchParams encode it for you:
const params = new URLSearchParams();
params.set("q", "cats & dogs");
params.set("page", 2);
console.log(params.toString());
console.log("https://example.com/search?" + params);
Assigning to location.href sends the browser to a new address. There are four related ways to move:
| Code | Does |
|---|---|
location.href = "/page.html" | go there (adds a history entry, like clicking a link) |
location.assign("/page.html") | the same, written as a method |
location.replace("/page.html") | go there without a history entry: Back skips the current page |
location.reload() | load the current page again |
// send the visitor to the home page
location.href = "/";
// like a redirect: the old page is not left in the Back list
location.replace("/login.html");
These are not shown with a Try It button because they would leave the page. Use them on a page of your own.
location.reload() that runs every time the page loads reloads forever. Always put navigation behind a condition or a click.
Changing only location.hash does not reload the page. It scrolls to the element with that id and adds a history entry, which is how in-page links work. The "hashchange" event tells you when it changes:
location.hash = "#intro"; // scroll to the element with id="intro"
window.addEventListener("hashchange", function () {
console.log("now at", location.hash);
});
textContent (not innerHTML), or someone can build a link that injects markup into your page.
Which property gives "?topic=json&level=2" for the current page?
location.hashlocation.searchlocation.pathnamelocation.hostsearch is the query string, starting with ?. hash starts with #, and pathname is the path.What does this log?
const p = new URLSearchParams("n=5");
console.log(typeof p.get("n"));
string. Values read from a query string are always text. Use Number(p.get("n")) to get a number.What is the difference between location.assign(url) and location.replace(url)?
assign adds a history entry, so the Back button returns to the current page. replace does not, so Back skips it.port to the address and a second tag value to the query, then read themrock & roll with URLSearchParams/home.html without leaving the current page in the Back list