Khi tạo cookie, dùng tham số path. Đường dẫn thư mục/trang đặt cookie. Để lấy cookie từ trang hiện tại, để trống path (mặc định cookie thuộc trang hiện tại).
Ví dụ
<!DOCTYPE html>
<html>
<head>
<script>
function ReadCookie() {
var allcookies = document.cookie;
document.write("All Cookies: " + allcookies + "<br>");
var cookiearray = allcookies.split(';');
for (var i = 0; i < cookiearray.length; i++) {
var name = cookiearray[i].split('=')[0].trim();
var value = cookiearray[i].split('=')[1];
document.write("Key: " + name + " - Value: " + value + "<br>");
}
}
</script>
</head>
<body>
<form name="myform">
<p>Nhấn nút để xem kết quả:</p>
<input type="button" value="Lấy Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>