Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธีดึง Hostname จาก URL ใน JavaScript

ใช้ URL API (Modern) หรือ location object เพื่อดึง hostname จาก URL ได้อย่างง่ายและน่าเชื่อถือ

ตัวอย่างจากบทความ

<!DOCTYPE html>
<html>
  <body>
    <script>
      var url = new URL("https://example.com/asdf/asdf/sadf.aspx?blah");
      document.write(url.hostname); // example.com
    </script>
  </body>
</html>

URL API Properties (Modern - แนะนำ)

const url = new URL('https://user:pass@sub.example.com:8080/path?name=value#hash');

url.href;        // Full URL
url.protocol;    // "https:"
url.host;        // "sub.example.com:8080" (hostname + port)
url.hostname;    // "sub.example.com" (แค่ hostname)
url.port;        // "8080"
url.pathname;    // "/path"
url.search;      // "?name=value"
url.searchParams; // URLSearchParams object
url.hash;        // "#hash"
url.username;    // "user"
url.password;    // "pass"
url.origin;      // "https://sub.example.com:8080" (protocol + host)

การใช้งานกับ URL String

// Relative URL ต้องมี base
const url1 = new URL('/path?query=1', 'https://example.com');
console.log(url1.hostname); // example.com

// Current page URL
const currentUrl = new URL(window.location.href);
console.log(currentUrl.hostname);

Legacy: location Object

// ใน Browser Context
window.location.hostname;    // "example.com"
window.location.host;        // "example.com:8080"
window.location.protocol;    // "https:"
window.location.pathname;    // "/path"
window.location.search;      // "?query=1"
window.location.hash;        // "#hash"
window.location.origin;      // "https://example.com"

// document.location เป็น alias ของ window.location

Regex Approach (ไม่แนะนำ)

// Error-prone, ไม่จัดการ edge cases
const hostname = url.match(/:\/\/(.[^/]+)/)[1]; // ไม่ครอบคลุมทุกกรณี

Node.js Environment

// Node.js 18+ มี global URL
const url = new URL('https://example.com/path');
console.log(url.hostname); // example.com

// Node.js เก่า: ใช้ url module
const { URL } = require('url');

Use Cases

1. Security - Validate Redirect

function safeRedirect(url, allowedDomains = ['example.com']) {
  try {
    const parsed = new URL(url);
    if (allowedDomains.includes(parsed.hostname)) {
      window.location.href = url;
    } else {
      console.error('Redirect blocked: unauthorized domain');
    }
  } catch (e) {
    console.error('Invalid URL');
  }
}

2. Analytics - Track External Links

document.querySelectorAll('a[href^="http"]').forEach(link => {
  link.addEventListener('click', () => {
    const hostname = new URL(link.href).hostname;
    if (hostname !== window.location.hostname) {
      analytics.track('external_link_click', { domain: hostname });
    }
  });
});

3. CORS Pre-check

async function fetchWithCorsCheck(url) {
  const targetHost = new URL(url).hostname;
  const currentHost = window.location.hostname;
  
  if (targetHost !== currentHost) {
    // Cross-origin - ต้องมี CORS headers
    const response = await fetch(url, { mode: 'cors' });
    return response.json();
  }
  // Same-origin
  return fetch(url).then(r => r.json());
}

Browser Support

  • URL API: Chrome 32+, Firefox 26+, Safari 10+, Edge 12+
  • URLSearchParams: Chrome 49+, Firefox 29+, Safari 10+, Edge 17+
  • IE: ไม่รองรับ (ต้อง Polyfill)