Để tạo cookie áp dụng cho toàn domain và subdomain, set thuộc tính domain và path:
domain=.example.com; path=/
Dấu chấm đầu .example.com bao gồm cả subdomain (www.example.com, api.example.com, v.v.).
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);
document.cookie = "name=" + cookievalue + "; domain=.example.com; path=/";
document.write("Đã đặt Cookie: 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>
Lưu ý: Chỉ có thể set domain cho domain hiện tại hoặc parent domain. Không thể set domain cho domain khác.