ใช้ 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 | คำอธิบาย | ตัวอย่าง |
|---|---|---|
href | URL เต็ม | "https://example.com/path?query#hash" |
protocol | Protocol | "https:" |
host | Host + Port | "example.com:8080" |
hostname | Hostname อย่างเดียว | "example.com" |
port | Port Number | "8080" |
pathname | Path | "/path/page.html" |
search | Query String | "?query=value" |
hash | Fragment | "#section" |
การใช้งานจริง
- Force HTTPS:
if (location.protocol !== 'https:') location.protocol = 'https:' - Conditional Loading: โหลด Resource แบบ Secure เฉพาะ HTTPS
- Analytics: บันทึก Protocol สถิติ