/

The URL Object: Explained and How to Use It

The URL Object: Explained and How to Use It

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:

1
const myURL = URL.createObjectURL(aBlob);

Once the blob URL has been obtained, it can be removed from memory using the URL.revokeObjectURL() function:

1
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:

1
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 fragment
  • host: the domain and port
  • hostname: the domain
  • href: the complete URL
  • origin: the scheme, domain, and port
  • password
  • 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