Để đặt cookie cho một trang cụ thể, bạn cần sử dụng thuộc tính “window.location.pathname”. Thuộc tính trả về đường dẫn và tên tệp của trang hiện tại.
Ví dụ
Bạn có thể thử chạy mã sau để triển khai cookie cho một trang cụ thể -
Bản trình diễn trực tiếp
<html> <head> <script> <!-- function WriteCookie() { if( document.myform.customer.value == "" ) { alert("Enter some value!"); return; } cookievalue= escape(document.myform.customer.value) + ";"; var myPath = window.location.pathname; document.cookie="name=" + cookievalue + ";path=myPath"; document.write ("Setting Cookies : " + "name=" + cookievalue ); } //--> </script> </head> <body> <form name = "myform" action = ""> Enter name: <input type="text" name="customer"/> <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/> </form> </body> </html>