Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Cách đặt cookie chỉ cho trang chủ bằng JavaScript

Để đặt cookie chỉ cho trang chủ, bạn cần thêm trang đó vào chính trang chủ.

Ví dụ

Bạn có thể chạy mã sau để đặt cookie:

<!DOCTYPE html>
<html>
<head>
    <script>
        function WriteCookie() {
            if (document.myform.customer.value === "") {
                alert("Vui lòng nhập giá trị!");
                return;
            }
            var cookievalue = escape(document.myform.customer.value) + ";";
            var myPath = window.location.pathname;
            var address = myPath.split("/");
            if (address[address.length - 1].toLowerCase() === "home.html") {
                document.cookie = "name=" + cookievalue;
                document.write("Đang đặt Cookie: name = " + cookievalue);
            }
        }
    </script>
</head>
<body>
    <form name="myform" action="">
        Nhập tên: <input type="text" name="customer"/>
        <input type="button" value="Đặt Cookie" onclick="WriteCookie()"/>
    </form>
</body>
</html>

Lưu ý: Hàm escape() đã bị deprecated, nên sử dụng encodeURIComponent() trong mã thực tế.