Để cookie chỉ áp dụng cho một trang cụ thể, dùng window.location.pathname làm giá trị path.
Ví dụ
<!DOCTYPE html>
<html>
<head>
<script>
function WriteCookie() {
if (document.myform.customer.value === "") {
alert("Vui lòng nhập giá trị!");
return;
}
var cookievalue = encodeURIComponent(document.myform.customer.value);
var myPath = window.location.pathname; // ví dụ: /page.html
document.cookie = "name=" + cookievalue + "; path=" + myPath;
document.write("Đã đặt Cookie cho trang này: name=" + cookievalue);
}
</script>
</head>
<body>
<form name="myform">
Nhập tên: <input type="text" name="customer"/>
<input type="button" value="Đặt Cookie" onclick="WriteCookie()"/>
</form>
</body>
</html>
Cookie này chỉ được gửi khi truy cập chính xác đường dẫn myPath.