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

Cách liệt kê tất cả cookie trên trang hiện tại bằng JavaScript

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>