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

วิธีดึง Protocol (http/https) ของเว็บเพจด้วย JavaScript

ใช้ window.location.protocol เพื่อดึง Protocol ของ URL ปัจจุบัน จะคืนค่า "http:" หรือ "https:" (มี Colon ต่อท้าย)

ตัวอย่างโค้ด

<!DOCTYPE html>
<html>
  <body>
    <script>
      document.write("Protocol: " + window.location.protocol);
    </script>
  </body>
</html>

คำอธิบาย

  • window.location.protocol — คืนค่า String เช่น "https:"
  • มี Colon (:) ต่อท้ายเสมอ
  • Read-only Property

Properties อื่นของ location

Propertyคำอธิบายตัวอย่าง
hrefURL เต็ม"https://example.com/path?query#hash"
protocolProtocol"https:"
hostHost + Port"example.com:8080"
hostnameHostname อย่างเดียว"example.com"
portPort Number"8080"
pathnamePath"/path/page.html"
searchQuery String"?query=value"
hashFragment"#section"

การใช้งานจริง

  • Force HTTPS: if (location.protocol !== 'https:') location.protocol = 'https:'
  • Conditional Loading: โหลด Resource แบบ Secure เฉพาะ HTTPS
  • Analytics: บันทึก Protocol สถิติ