Discover what a URL object is and learn how to effectively utilize it.
The URL object encompasses two static methods, URL.createObjectURL()
and URL.revokeObjectURL()
, which serve the purpose of manipulating URLs using blobs.
To generate a URL for a blob, the URL.createObjectURL()
function is employed. The process involves passing a blob as a parameter, resulting in the creation of a URL, as demonstrated below:
const myURL = URL.createObjectURL(aBlob);
Once the blob URL has been obtained, it can be removed from memory using the URL.revokeObjectURL()
function:
URL.revokeObjectURL(myURL);
Moreover, the URL object offers a distinct functionality through its constructor. By implementing the constructor, a URL object can be created. This is achieved by invoking the constructor with the URL of the current window, as showcased below:
const currentUrl = new URL(window.location.href);
Upon creating the URL object, various properties become available for inspecting the URL. Some noteworthy properties include:
hash
: the hash fragmenthost
: the domain and porthostname
: the domainhref
: the complete URLorigin
: the scheme, domain, and portpassword
pathname
port
protocol
search
searchParams
username
These properties correspond to the commonly known components of a URL. Additionally, it is possible to modify any of these properties, except for origin
and searchParams
, as they are read-only. To obtain a new URL string, one can use the toString()
method or directly reference the href
property.
Tags: URL object, createObjectURL, revokeObjectURL, URL constructor, manipulating URLs, blobs, JavaScript