Thuộc tính navigator.userAgent trả về chuỗi User-Agent header mà trình duyệt gửi đến server để nhận diện mình.
Cú pháp
navigator.userAgent
Ví dụ
<!DOCTYPE html>
<html>
<style>
body {
color: #000;
height: 100vh;
background: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%) no-repeat;
text-align: center;
}
.btn {
background: #db133a;
border: none;
height: 2rem;
border-radius: 20px;
width: 330px;
display: block;
color: #fff;
outline: none;
cursor: pointer;
margin: 1rem auto;
}
.show { font-size: 1.2rem; color: #fff; }
</style>
<body>
<h1>Demo navigator.userAgent</h1>
<button class="btn" onclick="display()">Hiển thị User-Agent</button>
<div class="show"></div>
<script>
function display() {
document.querySelector(".show").innerHTML =
"<p>Giá trị User-Agent header:</p>" +
"<p>" + navigator.userAgent + "</p>";
}
</script>
</body>
</html>
Kết quả
Nhấn "Hiển thị User-Agent". Kết quả ví dụ: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
Ứng dụng: Phát hiện trình duyệt, thiết bị, hệ điều hành (user agent parsing). Lưu ý: UA có thể bị giả mạo.