How to get the current URL with JavaScript?

Here’s a detailed guide to getting the current URL and its components in JavaScript, with examples for common use cases:

1. Get the Full URL

The simplest way to retrieve the entire URL of the current page:

const fullUrl = window.location.href;
console.log(fullUrl); // "https://www.example.com:8080/path/page.html?query=abc#section1"

2. Break Down URL Components

The window.location object provides access to specific parts of the URL:

PropertyDescriptionExample Output
protocolURL protocol (e.g., http:, https:)"https:"
hostHostname + port (if specified)"www.example.com:8080"
hostnameDomain name (without port)"www.example.com"
portPort number (empty if default)"8080"
pathnamePath after the domain"/path/page.html"
searchQuery string (including ?)"?query=abc"
hashFragment identifier (including #)"#section1"
originProtocol + hostname + port (read-only)"https://www.example.com:8080"

Example:

console.log(window.location.protocol); // "https:"
console.log(window.location.hostname); // "www.example.com"
console.log(window.location.pathname); // "/path/page.html"
console.log(window.location.search);   // "?query=abc"
console.log(window.location.hash);     // "#section1"

3. Get Query Parameters

Use URLSearchParams to parse the query string (e.g., ?query=abc&lang=en):

// Extract all parameters as key-value pairs
const params = new URLSearchParams(window.location.search);

// Get a specific parameter
const query = params.get('query'); // "abc"
const lang = params.get('lang');   // "en"

// Check if a parameter exists
if (params.has('query')) {
  console.log('Query exists');
}

// Convert to an object
const paramsObject = Object.fromEntries(params.entries());
console.log(paramsObject); // { query: "abc", lang: "en" }

4. Get the URL of the Referring Page

Use document.referrer to get the URL of the page that linked to the current page:

const referrer = document.referrer;
console.log(referrer); // "https://www.google.com" (if navigated from Google)

5. Practical Examples

Example 1: Redirect to a New Path

// Redirect to "/new-page" on the same domain
window.location.pathname = '/new-page';

Example 2: Check for a Hash Fragment

if (window.location.hash === '#success') {
  alert('Form submitted successfully!');
}

Example 3: Extract and Log All URL Components

const urlComponents = {
  FullURL: window.location.href,
  Protocol: window.location.protocol,
  Host: window.location.host,
  Path: window.location.pathname,
  QueryParams: Object.fromEntries(new URLSearchParams(window.location.search)),
  Hash: window.location.hash
};

console.log(urlComponents);

Example 4: Update Query Parameters

// Add or modify a query parameter
const params = new URLSearchParams(window.location.search);
params.set('page', '2'); // Set ?page=2

// Update the URL without reloading the page
window.history.replaceState({}, '', `${window.location.pathname}?${params}`);

6. Notes

  • Browser Only: These methods work in browsers, not in Node.js.
  • Dynamic Updates: window.location updates automatically when the URL changes (e.g., via pushState or manual navigation).
  • Security: Accessing certain parts (e.g., origin) is restricted by the same-origin policy for cross-origin iframes.

Summary Table

Method/PropertyUse Case
window.location.hrefGet the full URL
window.location.pathnameGet the path after the domain
URLSearchParamsParse and manipulate query strings
document.referrerGet the referring page URL
window.history.pushState()Modify the URL without reloading the page

By combining these tools, you can easily read, parse, and manipulate URLs in JavaScript!

Leave a Reply

Your email address will not be published. Required fields are marked *