ด้วย JavaScript คุณสามารถเข้าถึง/ อ่านคุกกี้ได้อย่างง่ายดายด้วยคุณสมบัติ “document.cookie” การอ่านคุกกี้นั้นง่ายพอๆ กับการเขียนหนึ่งอัน เนื่องจากค่าของอ็อบเจกต์ document.cookie คือคุกกี้
สตริง document.cookie จะเก็บรายการคู่ของ name=value คั่นด้วยเครื่องหมายอัฒภาค โดยที่ชื่อคือชื่อของคุกกี้ และค่าคือค่าสตริง
ตัวอย่าง
คุณสามารถลองเรียกใช้รหัสต่อไปนี้เพื่อเรียนรู้วิธีเข้าถึงคุกกี้โดยใช้วัตถุเอกสารใน JavaScript
สาธิตสด
<html>
<head>
<script>
<!--
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
// Get all the cookies pairs in an array
cookiearray = allcookies.split(';');
// Now take key value pair out of this array
for(var i=0; i<cookiearray.length; i++) {
name = cookiearray[i].split('=')[0];
value = cookiearray[i].split('=')[1];
document.write ("Key is : " + name + " and Value is : " + value);
}
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<p> click the following button and see the result:</p>
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>