Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Thuộc tính location.protocol trong JavaScript

Khái niệm

location.protocol trả về giao thức của URL hiện tại (bao gồm dấu hai chấm :). Thuộc tính chỉ đọc (read-only) của đối tượng Location.

Giá trị phổ biến

  • http:
  • https:
  • file: (mở file local)
  • blob:, data:, chrome-extension:, v.v.

Ví dụ cơ bản

<!DOCTYPE html>
<html lang="vi">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Location Protocol</title>
    <style>
        body { font-family: 'Segoe UI', sans-serif; padding: 20px; }
        .result { font-size: 18px; font-weight: 500; color: #6a1b9a; margin: 20px 0; padding: 15px; background: #f3e5f5; border-radius: 4px; }
        button { padding: 10px 20px; background: #1976d2; color: white; border: none; border-radius: 4px; cursor: pointer; }
        code { background: #e8eaf6; padding: 2px 6px; border-radius: 3px; }
    </style>
</head>
<body>
    <h1>Location Protocol Property</h1>
    <div class="result" id="result"></div>
    <button id="btn">LẤY PROTOCOL HIỆN TẠI</button>
    <h3>Nhấn nút để xem giao thức của URL hiện tại</h3>

    <script>
        const resEle = document.getElementById('result');
        const btnEle = document.getElementById('btn');

        btnEle.addEventListener('click', () => {
            resEle.innerHTML = `Giao thức hiện tại: ${location.protocol}`;
            
            // Thêm thông tin bổ sung
            resEle.innerHTML += `
URL đầy đủ: ${location.href}`; resEle.innerHTML += `
Host: ${location.host}`; resEle.innerHTML += `
Pathname: ${location.pathname}`; }); </script> </body> </html>

Kết quả

Chạy trên localhost: http:
Chạy trên production HTTPS: https:
Mở file local: file:

Ứng dụng thực tế

1. Kiểm tra HTTPS (Security)

if (location.protocol !== 'https:') {
    // Redirect to HTTPS
    location.href = location.href.replace('http:', 'https:');
}

2. Xác định API endpoint theo môi trường

const API_BASE = location.protocol === 'https:' 
    ? 'https://api.production.com' 
    : 'https://localhost:3000';

3. Kết hợp với location.origin

// origin = protocol + "//" + host
console.log(location.origin); 
// "https://example.com:443" hoặc "https://localhost:3000"

const apiUrl = `${location.origin}/api/users`;

Các thuộc tính Location liên quan

Thuộc tínhVí dụMô tả
hrefhttps://example.com:8080/path?query=1#hashURL đầy đủ
protocolhttps:Giao thức
hostexample.com:8080Domain + port
hostnameexample.comChỉ domain
port8080Port (rỗng nếu default)
pathname/pathĐường dẫn
search?query=1Query string
hash#hashFragment

Thay đổi URL (Navigation)

// Chuyển trang
location.href = 'https://newsite.com';
location.assign('https://newsite.com'); // Có history

// Thay thế trang hiện tại (không back được)
location.replace('https://newsite.com');

// Reload trang
location.reload();

// Chỉ thay đổi hash (không reload)
location.hash = 'section1';