About
This article shows you how to get and manipulate an URL with Javascript.
Type
URL object
You can manipulate an URL with the URL web API object 1)
- Build an URL object
const url = new URL(window.parent.location.href); // parent because this code runs in a iframe (if not delete it)
- Print a URL properties (…host, hostname,…)
console.log("Hostname: "+url.hostname); //
console.log("Path: "+url.pathname); //
- Manipulate the query string with https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
- Get a query parameter
console.log("Id Parameters: "+url.searchParams.get("id")); // none but it should work
- Set a query parameter
url.searchParams.set("id","#123");
console.log("Id Parameters After Setting: "+url.searchParams.get("id"));
- Print
console.log("New URL: "+url.toString());
Query Parameters
You can also manipulate only the URL Query Parameters.
Note that url.searchParams is available in a URL at url.searchParams.
const url = new URL("https://example.com/path?key1=value1&key2=value2");
const queryParams = new URLSearchParams(url.search);
console.log(`Size?: ${queryParams.size}`);
console.log(`Key1?: ${queryParams.has("key1")}`);
console.log(`GetKey1: ${queryParams.get("key1")}`);
console.log(`Set`);
queryParams.set("key3","value3");
console.log(`Delete`);
queryParams.delete("key1");
console.log(`toString: ${queryParams.toString()}`);
Ps: Note that searchParams is a iterator
How to get the url of the actual HTML page (with Javascript)
The value is stored in the href property
console.log("URL: "+window.parent.location.href); // url
// value is `about:srcdoc` because we are in a iframe
console.log("URL in iframe: "+window.location.href);
console.log("Path: "+window.parent.location.pathname);
- host is the endpoint ie hostname and port (if not the default HTTP port)
console.log("Host: "+window.parent.location.host);
- hostname - only the name of the host (ie without the port)
console.log("Hostname: "+window.parent.location.hostname);
console.log("Anchor: "+window.parent.location.hash);
- port (empty string if none)
console.log("Port: "+window.parent.location.port);
console.log("Protocol: "+window.parent.location.protocol);
- query string ?key=value
console.log("Query String: "+window.parent.location.search);
URL tied to a memory resource such as a file
The DOM URL.createObjectURL() and URL.revokeObjectURL() methods let you create data URL strings.
More Browser / Javascript - Object URL (createObjectURL / revokeObjectURL)